1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果在編譯時(shí)沒有指定它,您仍然需要在某處指定它。
如果在檢索 Json 數(shù)據(jù)之前指定,您可以簡(jiǎn)單地做一個(gè) switch case,將它解組到您想要的對(duì)象。
如果在Json 數(shù)據(jù)中指定,則可以json.RawMessage在確定適合哪種類型的結(jié)構(gòu)后將“靈活”部分編組到 a 中以進(jìn)行處理:
package main
import (
"encoding/json"
"fmt"
)
var s = `{"type":"structx", "data":{"x":9,"xstring":"This is structX"}}`
type JsonStruct struct {
Type string
Data json.RawMessage
}
type StructX struct {
X float64
Xstring string
}
type StructY struct {
Y bool
}
func main() {
var a *JsonStruct
err := json.Unmarshal([]byte(s), &a)
if err != nil {
panic(err)
}
switch a.Type {
case "structx":
// We Unmashal the RawMessage part into a StructX
var s *StructX
json.Unmarshal([]byte(a.Data), &s)
if err != nil {
panic(err)
}
fmt.Println(s)
case "structy":
// Do the same but for structY
}
}
- 1 回答
- 0 關(guān)注
- 165 瀏覽
添加回答
舉報(bào)