Using struct tags for decoding json is intended for the most common use cases. For custom behavior implement the Unmarshaler
interface (https://play.golang.org/p/rCpCDvWXGP):
type InnerStruct struct {
B, C string
}
type OuterStruct struct {
E string
A []InnerStruct
}
func (o *OuterStruct) UnmarshalJSON(bs []byte) error {
var intermediate map[string]json.RawMessage
err := json.Unmarshal(bs, &intermediate)
if err != nil {
return err
}
// e is just e
e, ok := intermediate["e"]
if !ok {
return fmt.Errorf("invalid json, expected `e`")
}
err = json.Unmarshal(e, &o.E)
if err != nil {
return err
}
// a is a or d
a, ok := intermediate["a"]
if !ok {
a, ok = intermediate["d"]
}
if !ok {
return fmt.Errorf("invalid json, expected `a` or `d`")
}
err = json.Unmarshal(a, &o.A)
if err != nil {
return err
}
return nil
}
In this case I used an intermediate map and delayed the processing of the inner values to match a
or d
. I'm sure this wasn't the actual data you had to work with, but hopefully it's enough to get you started.