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

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

如何使用 json.decoder 省略空 json 字段

如何使用 json.decoder 省略空 json 字段

Go
溫溫醬 2023-08-14 14:38:58
我嘗試理解為什么兩個函數返回相同的輸出。據我了解,省略空的目的是不將該鍵添加到結果結構中。我寫了這個例子,我期望第一個輸出沒有“Empty”鍵,但由于某種原因它的值仍然顯示為 0。package mainimport (    "encoding/json"    "fmt"    "strings")type agentOmitEmpty struct {    Alias   string `json:"Alias,omitempty"`    Skilled bool   `json:"Skilled,omitempty"`    FinID   int32  `json:"FinId,omitempty"`    Empty   int    `json:"Empty,omitempty"`}type agent struct {    Alias   string `json:"Alias"`    Skilled bool   `json:"Skilled"`    FinID   int32  `json:"FinId"`    Empty   int    `json:"Empty"`}func main() {    jsonString := `{        "Alias":"Robert",        "Skilled":true,        "FinId":12345    }`    fmt.Printf("output with omit emtpy: %v\n", withEmpty(strings.NewReader(jsonString)))    // output with omit emtpy: {Robert true 12345 0}    fmt.Printf("output regular: %v\n", withoutEmpty(strings.NewReader(jsonString)))    // output without omit: {Robert true 12345 0}}func withEmpty(r *strings.Reader) agentOmitEmpty {    dec := json.NewDecoder(r)    body := agentOmitEmpty{}    err := dec.Decode(&body)    if err != nil {        panic(err)    }    return body}func withoutEmpty(r *strings.Reader) agent {    dec := json.NewDecoder(r)    body := agent{}    err := dec.Decode(&body)    if err != nil {        panic(err)    }    return body}
查看完整描述

1 回答

?
森林海

TA貢獻2011條經驗 獲得超2個贊

您需要定義 Empty ,*int以便在沒有值時將其替換為 nil 。那么它就不會保存在數據庫中。



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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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