Go 有没有一种基于内容动态解组json的方法?
我有一个json格式,看起来像这样Go 有没有一种基于内容动态解组json的方法?,go,unmarshalling,Go,Unmarshalling,我有一个json格式,看起来像这样 { "my_object_list": [ { "meta": {"version": 1}, "my_value": {// Some complex value } } { "meta": {"version": 2}, "my_value": {// Some complex va
{
"my_object_list": [
{
"meta": {"version": 1},
"my_value": {// Some complex value
}
}
{
"meta": {"version": 2},
"my_value": {// Some complex value
}
}
]
}
我希望能够基于meta
封送每个my_值
,在golang中有没有实现这一点的方法
type MyResponse struct {
// how to I unmarshal each myObject base on version?
MyObjectList []myObject `json:"my_object_list"`
}
将变化的部分解组为一组。循环遍历数据并将原始消息数据解组为基于版本的类型
type V1Value struct{}
type myObject struct {
Meta struct {
Version int `json:"version"`
} `json:"meta"`
RawValue json.RawMessage `json:"my_value"`
Value interface{} `json:"-"`
}
type MyResponse struct {
MyObjectList []*myObject `json:"my_object_list"`
}
...
var response MyResponse
if err := json.Unmarshal(data, &response); err != nil {
// handle error
}
for _, o := range response.MyObjectList {
switch o.Meta.Version {
case 1:
var v V1Value
if err := json.Unmarshal(o.RawValue, &v); err != nil {
// handle error
}
o.Value = v
default:
// handle unknown version
}
}
您能为给定的输入json提供一个示例输出吗?只是为了确定要对
my_值执行什么样的更改
。这是一种利用解组器接口的变体