JSON 字段设置为 null 与字段不存在 [英] JSON field set to null vs field not there

查看:44
本文介绍了JSON 字段设置为 null 与字段不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 golang 中,有没有办法查看我是否可以区分设置为 null 的 json 字段与解组到结构中时不存在的 json 字段?因为两者都将结构中的值设置为 nil,但我需要知道该字段是否存在并查看是否有人将其设置为 null.

<代码>{"somefield1":"somevalue1",somefield2":空}

VS

<代码>{"somefield1":"somevalue1",}

当解组到结构中时,两个 json 都将为零.任何有用的资源将不胜感激!

解决方案

在决定做某事之前,使用 json.RawMessage 来延迟"解组过程以确定原始字节:

var data = []byte(`{"somefield1":"somevalue1",somefield2":空}`)类型数据结构{SomeField1 字符串SomeField2 json.RawMessage}功能主(){d := &数据{}_ = json.Unmarshal(data, &d)fmt.Println(d.SomeField1)如果 len(d.SomeField2) >0 {if string(d.SomeField2) == "null" {fmt.Println("somefield2 在那里但为空")} 别的 {fmt.Println("somefield2 在那里并且不为空")//对数据做一些事情}} 别的 {fmt.Println("somefield2 不存在")}}

看游乐场https://play.golang.org/p/Wganpf4sbO

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",
}

Both jsons will be nil when unmarshalled into a struct. Any useful resources will be very appreciated!

解决方案

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")
    }
}

See the playground https://play.golang.org/p/Wganpf4sbO

这篇关于JSON 字段设置为 null 与字段不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆