Is there a way to dynamically unmarshal json base on content? [duplicate]

核能气质少年 提交于 2021-02-08 12:13:48

问题


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
            }
        }
    ]
}

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"`
}

回答1:


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
    }
}


来源:https://stackoverflow.com/questions/58073214/is-there-a-way-to-dynamically-unmarshal-json-base-on-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!