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

标签 json go struct null

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

{
  "somefield1":"somevalue1",
  "somefield2":null
}

VS

{
  "somefield1":"somevalue1",
}

当解码为结构时,两个 json 都将为 nil。 任何有用的资源将不胜感激!

最佳答案

在决定做某事之前,使用 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")
    }
}

看 Playground https://play.golang.org/p/Wganpf4sbO

关于JSON 字段设置为 null vs 字段不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36601367/

相关文章:

java - 使用java bean转换json格式

php - 在 yii 中查询后返回 JSON

json - 如何处理具有与 json 响应不同的 json 键的结构

arrays - 如何将 []string 转换为 ...string

pointers - Golang 复制包含指针的结构

c - 为什么普通变量不允许位域?

c++ - 为什么编译器在 C/C++ 中填充结构?

java - 如何区分 Spring Rest Controller 中部分更新的 null 值和未提供的值

goroutine 睡着了 - 死锁

c++ - 如何在结构体中声明填充?