Unmarshalling JSON to Embedded Structures in Go
Deserialization of JSON data into embedded structures can present challenges in Golang. Take the example struct:
<code class="go">type Outer struct { Inner Num int } type Inner struct { Data string }</code>
When using json.Unmarshal(data, &Outer{}), only the Inner field is unmarshaled, ignoring the Num field. To understand why this occurs, it's important to note that Inner is embedded in Outer.
During JSON unmarshaling, the library calls the unmarshaler on Outer, which in turn calls the unmarshaler on Inner. Consequently, the Inner.UnmarshalJSON function receives the entire JSON string, which it processes for Inner alone.
To resolve this issue, make Inner an explicit field in Outer. This ensures that during JSON unmarshaling, the Inner field is properly unmarshaled, and the Num field is set based on the JSON data:
<code class="go">Outer struct { I Inner // Make Inner an explicit field Num int `json:"Num"` }</code>
This modification enables the correct unmarshaling of JSON data into the Outer struct, including both Inner and Num fields.
The above is the detailed content of Why is my `Num` field ignored when unmarshalling JSON to an embedded struct in Go?. For more information, please follow other related articles on the PHP Chinese website!