JSON字段设置为null vs字段不存在

JSON字段设置为null vs字段不存在,第1张

JSON字段设置为null vs字段不存在

使用

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5475339.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存