Unmarshal JSON array of heterogeneous structures

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?

+7
source share
1 answer

I think your process is probably a little more complicated than it should be, see http://play.golang.org/p/0gahcMpuQc . One interface [string] [string] will handle a lot for you.

Alternatively, you can create a type like

 struct EntityUnion { Type string // Fields from t1 // Fields from t2 // ... } 

Undo it; it will set the Type string and fill in all the fields that it can get from JSON data. Then you just need a little function to copy fields to a specific type.

+5
source

All Articles