根据键解析JSON

3

我需要从网络接收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个回答

5

只需创建一个同时包含两个字段的类型:

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

将JSON解组成该类型,然后检查Foo和/或Bar是否为nil,以了解您正在处理的数据。

这是一个演示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"`
}

FooBar 字段是指针类型,因为值类型字段会使得确定哪个字段被设置变得更加繁琐。 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")
}

仅此而已,没有更多了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接