本文介绍了有没有一种方法可以根据内容动态解组json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的json格式

I have a json format that looks like this

{
    "my_object_list": [
        {
            "meta": {"version": 1},
            "my_value": {// Some complex value
            }
        }
        {
            "meta": {"version": 2},
            "my_value": {// Some complex value
            }
        }
    ]
}

我希望能够根据 meta 封送每个 my_value ,有没有办法在golang中实现这一目标?

I want to be able to marshal each of the my_value base on meta is there a way to achieve that in golang?

type MyResponse struct {
    // how to I unmarshal each myObject base on version?
    MyObjectList     []myObject   `json:"my_object_list"`
}

推荐答案

将可变部分解组为 json.RawMessage .遍历数据并将原始消息数据解组为基于版本的类型.

Unmarshal the varying part to a json.RawMessage. Loop through the data and unmarshal the raw message data to a type based on the version.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:50