Open DonDebonair opened 2 years ago
I also don't figure out how to implement deserialization based on the discriminator field. @DonDebonair have you found a solution?
Yeah, I did. I'm using YAML, not JSON. But the principles are the same. This is roughly how I approached it:
type Animals struct {
Animals []map[string]any `yaml:"animals"`
}
func myFunc() {
animalsConfig := &Animals{}
err = yaml.Unmarshal(b, animals)
}
mapstruct
to unmarshal into actual structsfunc myFunc() {
...
for _, animal := range animalsConfig.Animals {
var animalThing Animal // Animal interface is defined somewhere
if animal["type] == "dog" {
animalThing = Dog{}
}
if animal["type"] == "cat" {
animalThing = Cat{}
}
// Etc., you should probably use a switch/case here? ^
err = mapstructure.Decode(deployment, animalThing)
if err != nil {
return nil, err
}
animals = append(animals, animalThing)
}
}
In the Buy Why?! section in the README is says:
How would you go about this, if the JSON looks like this?:
In this case, each of the items in the
animals
array would adhere to the same interface (for example something that implementsName()
) but each differenttype
would correspond to a different struct type that implements said interface.The README suggests that this is what
mapstructure
is practically made for, but I don't understand how to implement this.