Raf*_*yan 3 json go unmarshalling
我从网络接收 JSON 格式的数据,我需要根据密钥对其进行解组。
这是数据示例:
{
"foo": {
"11883920": {
"fieldA": 123,
"fieldB": [
{
"fieldC": "a",
"fieldD": 1173653.22
}
]
}
},
"bar": {
"123": {
"fieldE": 123
}
}
"anyOtherkey": {...}
}
Run Code Online (Sandbox Code Playgroud)
逻辑是,如果 key 是,foo
则应将其解组为fooStruct
,如果bar
- 则应解组为barStruct
。实现这个逻辑的最佳方法是什么?(我不想将其解组map[string]interface{}
,也许可以使用json.NewDecoder()
函数,但我无法获得预期的结果)。
只需创建一个包含两个字段的类型:
type MyType struct {
Foo *fooStruct `json:"foo,omitempty"`
Bar *barStruct `json:"bar,omitempty"`
OtherKey string `json:"other_key"`
}
Run Code Online (Sandbox Code Playgroud)
将 JSON 解组为该类型,然后只需检查 igFoo
和 orBar
是否为 nil 即可了解您正在使用的数据。
这是一个游乐场演示,展示了它的样子
其本质是:
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"`
}
Run Code Online (Sandbox Code Playgroud)
和字段是指针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")
}
Run Code Online (Sandbox Code Playgroud)
也仅此而已