doulutian4843 2019-01-25 10: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 11: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

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

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址