Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding structs in different JSON mappings

Tags:

json

go

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"`
}
like image 664
Patrick Reck Avatar asked Apr 01 '26 16:04

Patrick Reck


1 Answers

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.

like image 112
Ainar-G Avatar answered Apr 03 '26 07:04

Ainar-G