-2

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"`
}
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
user10714010
  • 865
  • 2
  • 13
  • 20
  • Can you provide an example output for given input json? Just to be sure what kind of changes you want to perform on `my_value`. – Kamol Hasan Sep 24 '19 at 05:08

1 Answers1

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
    }
}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242