doulutian4843 2019-01-25 02:57
浏览 64
已采纳

根据密钥解组JSON

I am receiving JSON formatted data from the network, and I need to unmarshal it depending on a key.
Here is the data example:

{
  "foo": {
    "11883920": {
      "fieldA": 123,
      "fieldB": [
        {
          "fieldC": "a",
          "fieldD": 1173653.22
        }
      ]
    }
  },
  "bar": {
     "123": {
       "fieldE": 123
     }
   }
  "anyOtherkey": {...}
}

The logic is that, if the key is foo it sould be unmarshaled as fooStruct, and if bar - as a barStruct. What is the best way to implement this logic? (I don't want to unmarshal it to map[string]interface{}, maybe it is possible with json.NewDecoder() function but I could not get the expected result).

  • 写回答

1条回答 默认 最新

  • dongsong8932 2019-01-25 03:02
    关注

    Just create a type with both fields present:

    type MyType struct {
        Foo      *fooStruct `json:"foo,omitempty"`
        Bar      *barStruct `json:"bar,omitempty"`
        OtherKey string     `json:"other_key"`
    }
    

    Unmarshal the JSON into that type, and simply check ig Foo and or Bar are nil to know what data you're working with.

    Here's a playground Demo of what this would look like

    The essence of it is:

    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"`
    }
    

    The Foo and Bar fields are pointer types, because value fields would make it a bit more cumbersome to work out which field was actually set. The omitempty bit allows you to marshal the same type to recreate the original payload, as nil values will just not show up in the output.

    To check which field was set in the original JSON string, simply write:

    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")
    }
    

    Nothing more too it

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部