处理 json 响应中的 NULL 值

我对 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")

    }

}

现在,我的主要问题是:


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


例如,在下面的示例中,我无法知道水果的价格是否尚未设定或实际价格为零。


你们如何处理这个问题?


在其他语言中,字符串和整数都可以为 null,但 Go 中并非如此。


收到一只叮咚
浏览 235回答 1
1回答

繁星coding

使用指针:type Fruit struct {    Name    *string `json:"Name,omitempty"`    Price   *int     `json:"Price,omitempty"`    Owner   *string  `json:"Owner,omitempty"`}然后你可以检查一个字段是否为零,或者它是否有值。但是,如果您想区分文档中存在某个字段并设置为 null 的情况和该字段根本不存在的情况,这对您没有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go