为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
饮歌长啸 2022-01-04 13:32:28
在 golang 中,有没有办法查看我是否可以区分设置为 null 的 json 字段与解组到结构中时不存在的 json 字段?因为两者都将结构中的值设置为 nil,但我需要知道该字段是否存在并查看是否有人将其设置为 null。{  "somefield1":"somevalue1",  "somefield2":null}VS{  "somefield1":"somevalue1",}当解组到结构中时,两个 jsons 都将为零。任何有用的资源将不胜感激!
查看完整描述

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


查看完整回答
反对 回复 2022-01-04
?
拉丁的传说

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


查看完整回答
反对 回复 2022-01-04
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

如果您将对象解组到 map[string]interface{} 中,那么您只需检查是否存在字段


type unMarshalledObject map[string]interface{}

json.Unmarshal(input, unMarshalledObject)

_, ok := unMarshalledObject["somefield2"]


查看完整回答
反对 回复 2022-01-04
  • 3 回答
  • 0 关注
  • 322 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号