问题
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