I am trying to decode two different responses with the same properties, the only difference is the names of the JSON mappings they come from.
What is the proper way to achieve the demonstrated below?
type ResponseProperties struct {
CurrentPage uint
TotalPages uint
Events []TrackingEvent
}
type TrackingResponse struct {
// ResponseProperties
CurrentPage uint `json:"current_page"`
TotalPages uint `json:"total_pages"`
Events []TrackingEvent `json:"clicks"`
}
type SubscriberResponse struct {
// ResponseProperties
CurrentPage uint `json:"current_page"`
TotalPages uint `json:"total_pages"`
Events []TrackingEvent `json:"subscribers"`
}
I'd suggest just keeping them separate. You never know when an API response suddenly changes.
But if you do want to unmarshal everything into one struct, one way to do this is to unmarshal into a struct that has fields for all possible aliases and then assign the one that is not empty. E.g.:
type Basket struct {
NumFruit int
Fruits []string // Can be either "Apples" or "Oranges" in JSON.
}
func (bskt *Basket) UnmarshalJSON(b []byte) error {
type Basket_ Basket
v := struct {
Basket_
Apples, Oranges []string
}{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
*bskt = Basket(v.Basket_)
if v.Apples != nil {
bskt.Fruits = v.Apples
}
if v.Oranges != nil {
bskt.Fruits = v.Oranges
}
return nil
}
Playground: http://play.golang.org/p/pLe5EwsYEP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With