3 回答

TA貢獻1865條經(jīng)驗 獲得超7個贊
如果您沒有結(jié)構(gòu)化數(shù)據(jù)并且確實需要發(fā)送完整的 JSON,那么您可以這樣閱讀:
// an arbitrary json string
jsonString := "{\"foo\":{\"baz\": [1,2,3]}}"
var jsonMap map[string]interface{}
json.Unmarshal([]byte(jsonString ), &jsonMap)
fmt.Println(jsonMap)
// prints: map[foo:map[baz:[1 2 3]]]
當然,這有一個很大的缺點,因為您不知道每個項目的內(nèi)容是什么,因此您需要在使用之前將對象的每個子項強制轉(zhuǎn)換為其正確的類型。
// inner items are of type interface{}
foo := jsonMap["foo"]
// convert foo to the proper type
fooMap := foo.(map[string]interface{})
// now we can use it, but its children are still interface{}
fmt.Println(fooMap["baz"])
如果您發(fā)送的 JSON 可以更加結(jié)構(gòu)化,則可以簡化此操作,但是如果您想接受任何類型的 JSON 字符串,那么您必須在使用數(shù)據(jù)之前檢查所有內(nèi)容并轉(zhuǎn)換為正確的類型。
您可以在此 Playground 中找到運行的代碼。

TA貢獻1831條經(jīng)驗 獲得超10個贊
如果我正確理解您的問題,您想使用json.RawMessageas Context。
RawMessage 是原始編碼的 JSON 對象。它實現(xiàn)了 Marshaler 和 Unmarshaler,可用于延遲 JSON 解碼或預先計算 JSON 編碼。
RawMessage 只是[]byte,因此您可以將其保存在數(shù)據(jù)存儲中,然后將其作為“預先計算的 JSON”附加到傳出消息中。
type Iot struct {
Id int `json:"id"`
Name string `json:"name"`
Context json.RawMessage `json:"context"` // RawMessage here! (not a string)
}
func main() {
in := []byte(`{"id":1,"name":"test","context":{"key1":"value1","key2":2}}`)
var iot Iot
err := json.Unmarshal(in, &iot)
if err != nil {
panic(err)
}
// Context is []byte, so you can keep it as string in DB
fmt.Println("ctx:", string(iot.Context))
// Marshal back to json (as original)
out, _ := json.Marshal(&iot)
fmt.Println(string(out))
}
https://play.golang.org/p/69n0B2PNRv

TA貢獻1817條經(jīng)驗 獲得超14個贊
我也不知道你到底想做什么,但是在go 中我知道兩種將接收到的數(shù)據(jù)轉(zhuǎn)換為 json 的方法。此數(shù)據(jù)應(yīng)為[]byte類型
首先是允許編譯器選擇接口并嘗試以這種方式解析為 JSON:
[]byte(`{"monster":[{"basic":0,"fun":11,"count":262}],"m":"18"}`)
bufferSingleMap map[string]interface{}
json.Unmarshal(buffer , &bufferSingleMap)
如果您知道收到的數(shù)據(jù)的外觀如何,您可以先定義結(jié)構(gòu)
type Datas struct{
Monster []struct {
Basic int `json:"basic"`
Fun int `json:"fun"`
Count int `json:"count"`
} `json:"Monster"`
M int `json:"m"`
}
Datas datas;
json.Unmarshal(buffer , &datas)
重要的是名稱值。應(yīng)該用大寫字母(Fun, Count) 這個是Unmarshal的標志,應(yīng)該是json。如果您仍然無法解析為 JSON 向我們展示您收到的數(shù)據(jù),可能是它們的語法錯誤
- 3 回答
- 0 關(guān)注
- 248 瀏覽
添加回答
舉報