caiman
caiman

Reputation: 425

Adjusting the structure when unmarshalling json in go

Unmarshalling JSON (that I do not control) like this:

{
    "states": {
        "state": [
            { ...}
        ]
    }
}

into a struct like:

type Device struct {
    States    struct{ State []State }
}
var dev Device

I get an ugly syntax to access a state:

dev.States.State[0]

I would like to be able to transform the object so I can do

dev.States[0]

Can this be done with tags (omitted in the above example because not needed), or with another method, or do I have to first unmarshal to a struct like the above then manually remap to a struct as I want it?

Upvotes: 5

Views: 176

Answers (1)

Yandry Pozo
Yandry Pozo

Reputation: 5123

All you have to do is implement the Unmarshaler interface just adding the method UnmarshalJSON(data []byte) error and including the logic that you need after Unmarshal; and if you want to do the inverse operation(marshal) just implement the Marshaler interface.

type State struct {
    Name string `json:"name"`
}

type Device struct {
    States []State
}

func (dev *Device) UnmarshalJSON(data []byte) error {

    // anonymous struct with the real backbone of the json
    tmp := struct {
        States struct {
            State []State `json:"state"`
        } `json:"states"`
    }{}

    if err := json.Unmarshal(data, &tmp); err != nil {
        return err
    }

    dev.States = tmp.States.State

    return nil
}

Full example: https://play.golang.org/p/gNpS13ED_i

Upvotes: 6

Related Questions