JSON字段设置为null vs字段不存在 [英] JSON field set to null vs field not there
问题描述
在golang中,有没有一种方法可以查看是否可以将解编为结构的json字段与设置为null的json字段区分开?因为两者都将struct中的值设置为nil,但是我需要知道该字段是否以该字段开头,并查看是否有人将其设置为null.
Is there a way, in golang, to see if I can differentiate between a json field being set to null vs a json field not being there when unmarshalled into a struct? Because both set the value in the struct to be nil, but I need to know if the field was there to begin with and to see if someone set it to null.
{
"somefield1":"somevalue1",
"somefield2":null
}
VS
{
"somefield1":"somevalue1",
}
两个jsons在解组为结构时都将为零. 任何有用的资源将不胜感激!
Both jsons will be nil when unmarshalled into a struct. Any useful resources will be very appreciated!
推荐答案
在决定做某事之前,使用json.RawMessage
延迟"解编组过程以确定原始字节:
Use json.RawMessage
to "delay" the unmarshaling process to determine the raw byte before deciding to do something:
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
这篇关于JSON字段设置为null vs字段不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!