3 回答

TA貢獻1836條經驗 獲得超5個贊
用于json.RawMessage在決定做某事之前“延遲”解組過程以確定原始字節:
var data = []byte(`{
"somefield1":"somevalue1",
"somefield2": null
}`)
type Data struct {
SomeField1 string
SomeField2 json.RawMessage
}
func main() {
d := &Data{}
_ = json.Unmarshal(data, &d)
fmt.Println(d.SomeField1)
if len(d.SomeField2) > 0 {
if string(d.SomeField2) == "null" {
fmt.Println("somefield2 is there but null")
} else {
fmt.Println("somefield2 is there and not null")
// Do something with the data
}
} else {
fmt.Println("somefield2 doesn't exist")
}
}
看操場https://play.golang.org/p/Wganpf4sbO

TA貢獻1789條經驗 獲得超8個贊
好問題。
我相信你可以使用https://golang.org/pkg/encoding/json/#RawMessage作為:
type MyMessage struct {
somefield1 string
somefield2 json.RawMessage
}
因此,解組后,你應該[]byte("null")在的情況下,null和nil如果它丟失了。
這是一個游樂場代碼:https : //play.golang.org/p/UW8L68K068

TA貢獻1813條經驗 獲得超2個贊
如果您將對象解組到 map[string]interface{} 中,那么您只需檢查是否存在字段
type unMarshalledObject map[string]interface{}
json.Unmarshal(input, unMarshalledObject)
_, ok := unMarshalledObject["somefield2"]
- 3 回答
- 0 關注
- 241 瀏覽
添加回答
舉報