tochiai tochiai - 3 months ago 16
JSON Question

json unmarshal embedded struct

I would like to unmarshal to struct

Outer
defined as:

type Outer struct {
Inner
Num int
}

type Inner struct {
Data string
}
func (i *Inner) UnmarshalJSON(data []byte) error {
i.Data = string(data)
return nil
}


Using
json.Unmarshal(data, &Outer{})
seems only to use
Inner
's
UnmarshalJSON
and ignores the
Num
field: https://play.golang.org/p/WUBfzpheMl

I have an unwieldy solution where I set the
Num
field manually, but I was wondering if anybody had a cleaner or simpler way to do it.

Thanks!

Answer

This is happening because Inner is being embedded in Outer. That means when json library calls unmarshaler on Outer, it instead ends up calling it on Inner.

Therefore, inside func (i *Inner) UnmarshalJSON(data []byte), the data argument contains the entire json string, which you are then processing for Inner only.

You can fix this by making Inner explicit field in Outer

Outer struct {
    I Inner // make Inner an explicit field
    Num int `json:"Num"`
}

Working example

Comments