Say I want to be able to handle both nested and unnested json
s of the following form, as in this example:
source_json_1 := `{"owner": "John", "nickname": "Rose", "species": "Dog"}`
source_json_2 := `{"owner": "Doe", "Pet": [{"nickname": "Rose", "species": "Dog"},
{"nickname": "Max", "species": "Cat"}]}`
If I define Pet
as an embedded struct I can easily unmarshal it with:
type Owner struct {
Name string
Pet
}
type Pet struct {
NickName string
Species string
}
Resulting in John's pet getting adequately marshalled.
{John {Rose Dog}}
{Doe { }}
But since Pet
can actually also be a slice of Pet
s, Doe's Pet
s are not correctly unmarshalled. If instead go with
type Owner struct {
Name string
Pet []Pet
}
Then Doe gets marshalled just fine.
{John []}
{Doe [{Rose Dog} {Max Cat}]}
How can I catch both cases?
I'd prefer to marshall it into a slice of Pet
s in the end, no matter what.
You're looking at two separate data structures, so to unmarshal them with a single struct
type, you'd need to account for both:
type Owner struct {
Name string
Pet
Pets []Pet `json:"Pet"`
}
Then, if you want the slice to be authoritative, after you unmarshall, move the embedded to the slice:
// owner := unmarshall blah blah
if owner.Pet != Pet{} {
owner.Pets = append(owner.Pets, owner.Pet)
}