I want to deserialise an object that includes an array of a some interface Entity
:
type Result struct {
Foo int;
Bar []Entity;
};
Entity
is an interface that is implemented by a number of struct types. JSON data identifies the struct type with a "type" field in each entity. E.g.
{"type":"t1","field1":1}
{"type":"t2","field2":2,"field3":3}
How would I go about deserialising the Result
type in such a way that it correctly populates the array. From what I can see, I have to:
- Implement
UnmarshalJSON
onResult
. - Parse
Bar
as a[]*json.RawMessage
. - Parse each raw message as
map[string]interface{}
. - Check "type" field in the raw message.
- Create a struct of appropriate type.
- Parse the raw message again, this time into the just created struct.
This all sounds very tedious and boring. Is there a better way to do this? Or am I doing it backwards, and there is a more canonical method to handle an array of heterogeneous objects?