根据密钥解组 JSON

我正在从网络接收 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()函数,但我无法获得预期的结果)。


月关宝盒
浏览 132回答 1
1回答

GCT1015

只需创建一个同时包含两个字段的类型: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 Payloadif 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")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go