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 关注
- 321 浏览
添加回答
举报
