I want to deserialize an object that includes an array of some Entity interface:
type Result struct { Foo int; Bar []Entity; };
Entity is an interface that is implemented by several types of structures. JSON data identifies the type of structure with a type field in each object. For example.
{"type":"t1","field1":1} {"type":"t2","field2":2,"field3":3}
How would I decide to deserialize the Result type so that it fills the array correctly. From what I see, I should:
UnmarshalJSON in Result .- Parse
Bar as []*json.RawMessage . - Parse each raw message as
map[string]interface{} . - Check the "type" field in the raw message.
- Create a structure of the appropriate type.
- Analyze the raw message again, this time into the structure you just created.
It sounds very tiring and boring. Is there a better way to do this? Or am I doing this back, and is there a more canonical method for processing an array of heterogeneous objects?
Alex b
source share