【问题标题】:Deal with NULL values in json response [duplicate]处理json响应中的NULL值[重复]
【发布时间】:2019-11-01 14:39:04
【问题描述】:

我对 Go 中 json null 值的处理感到困惑。 假设我有以下示例:

package main

import (
    "fmt"
    "encoding/json"
    "log"
)

type Fruit struct {
    Name    string
    Price   int
    Owner   string  
}




func main() {
jsonData := []byte(`
{
    "Name": "Standard",
    "Price" : null,
    "Owner": null
}`)

    var f Fruit
    err := json.Unmarshal(jsonData, &f)
    if err != nil {
            log.Println(err)
    }
    fmt.Printf("Name is : %s\nPrice is : %d\nOwner is : %s\n", f.Name, f.Price, f.Owner)
    if f.Owner == ""  {
        fmt.Printf("Name should be nil?\n")
    }
    if f.Price == 0  {
        fmt.Printf("Price should be nil?\n")
    }
}

现在,我的主要问题是:

区分零值和默认值的正确方法是什么?

例如,在下面的示例中,我无法知道水果的价格是没有设置还是实际价格为零。

你们是怎么处理这个问题的?

在其他语言中,字符串和整数都可以为空,但在 Go 中不是这样。

【问题讨论】:

  • 使用指针类型,例如*int/*string.

标签: json go null


【解决方案1】:

使用指针:

type Fruit struct {
    Name    *string `json:"Name,omitempty"`
    Price   *int     `json:"Price,omitempty"`
    Owner   *string  `json:"Owner,omitempty"`
}

然后你可以检查一个字段是否为nil,或者它是否有值。

但是,如果您想区分文档中存在字段并设置为 null 和该字段根本不存在的情况,这对您没有帮助。

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多