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

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

JSON 字段設置為 null 與字段不存在

JSON 字段設置為 null 與字段不存在

Go
飲歌長嘯 2022-01-04 13:32:28
在 golang 中,有沒有辦法查看我是否可以區分設置為 null 的 json 字段與解組到結構中時不存在的 json 字段?因為兩者都將結構中的值設置為 nil,但我需要知道該字段是否存在并查看是否有人將其設置為 null。{  "somefield1":"somevalue1",  "somefield2":null}VS{  "somefield1":"somevalue1",}當解組到結構中時,兩個 jsons 都將為零。任何有用的資源將不勝感激!
查看完整描述

3 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

用于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")

    }

}

看操場https://play.golang.org/p/Wganpf4sbO


查看完整回答
反對 回復 2022-01-04
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

好問題。


我相信你可以使用https://golang.org/pkg/encoding/json/#RawMessage作為:


type MyMessage struct {

  somefield1 string

  somefield2 json.RawMessage

}

因此,解組后,你應該[]byte("null")在的情況下,null和nil如果它丟失了。


這是一個游樂場代碼:https : //play.golang.org/p/UW8L68K068


查看完整回答
反對 回復 2022-01-04
?
慕姐8265434

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

如果您將對象解組到 map[string]interface{} 中,那么您只需檢查是否存在字段


type unMarshalledObject map[string]interface{}

json.Unmarshal(input, unMarshalledObject)

_, ok := unMarshalledObject["somefield2"]


查看完整回答
反對 回復 2022-01-04
  • 3 回答
  • 0 關注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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