douchuo1963 2016-04-13 14:22
浏览 1327
已采纳

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

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!

  • 写回答

5条回答 默认 最新

  • douxiong3234 2016-04-13 14:40
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊