亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

處理 json 響應中的 NULL 值

處理 json 響應中的 NULL 值

Go
收到一只叮咚 2023-07-31 16:40:18
我對 Go 中 json null 值的處理感到困惑??梢哉f我有以下示例:package mainimport (    "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 中并非如此。
查看完整描述

1 回答

?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

使用指針:


type Fruit struct {

    Name    *string `json:"Name,omitempty"`

    Price   *int     `json:"Price,omitempty"`

    Owner   *string  `json:"Owner,omitempty"`

}


然后你可以檢查一個字段是否為零,或者它是否有值。


但是,如果您想區分文檔中存在某個字段并設置為 null 的情況和該字段根本不存在的情況,這對您沒有幫助。


查看完整回答
反對 回復 2023-07-31
  • 1 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號