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

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

根據密鑰解組 JSON

根據密鑰解組 JSON

Go
月關寶盒 2023-06-01 18:13:43
我正在從網絡接收 JSON 格式的數據,我需要根據密鑰對其進行解組。這是數據示例:{  "foo": {    "11883920": {      "fieldA": 123,      "fieldB": [        {          "fieldC": "a",          "fieldD": 1173653.22        }      ]    }  },  "bar": {     "123": {       "fieldE": 123     }   }  "anyOtherkey": {...}}邏輯是,如果密鑰是,foo則應將其解組為fooStruct,如果bar- 作為barStruct. 實現此邏輯的最佳方法是什么?(我不想將其解組為map[string]interface{},也許可以使用json.NewDecoder()函數,但我無法獲得預期的結果)。
查看完整描述

1 回答

?
GCT1015

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

只需創建一個同時包含兩個字段的類型:


type MyType struct {

    Foo      *fooStruct `json:"foo,omitempty"`

    Bar      *barStruct `json:"bar,omitempty"`

    OtherKey string     `json:"other_key"`

}

將 JSON 解組為該類型,只需檢查 igFoo和 or Barare nil 即可了解您正在使用的數據。


這是一個 playground Demo,展示了它的樣子


它的本質是:


type Foo struct {

    Field int `json:"field1"`

}


type Bar struct {

    Message string `json:"field2"`

}


type Payload struct {

    Foo   *Foo   `json:"foo,omitempty"`

    Bar   *Bar   `json:"bar,omitempty"`

    Other string `json:"another_field"`

}

和字段是指針類型,因為值字段會使確定實際設置Foo了Bar哪個字段變得更加麻煩。該omitempty位允許您編組相同的類型以重新創建原始有效負載,因為nil值不會顯示在輸出中。


要檢查原始 JSON 字符串中設置了哪個字段,只需編寫:


var data Payload

if err := json.Unmarshal([]byte(jsonString), &data); err != nil {

    // handle error

}

if data.Foo == nil && data.Bar == nil {

    // this is probably an error-case you need to handle

}

if data.Foo == nil {

    fmt.Println("Bar was set")

} else {

    fmt.Println("Foo was set")

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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