Home >Backend Development >Golang >Why does JSON Unmarshaling of Embedded Structs Lead to Unexpected Behavior?
JSON Unmarshal embedded struct Exploration
When attempting to unmarshal a JSON object into a struct with an embedded field, unexpected behavior can arise. To illustrate this, consider the following struct definitions:
<code class="go">type Outer struct { Inner Num int } type Inner struct { Data string } func (i *Inner) UnmarshalJSON(data []byte) error { i.Data = string(data) return nil }</code>
Unmarshalling a JSON object into an instance of Outer using json.Unmarshal(data, &Outer{}) results in only the Inner field being populated, while the Num field remains untouched. This can be attributed to the way JSON unmarshals embedded fields.
To resolve this issue, it is recommended to make the embedded field an explicit field in the parent struct. This modification allows the JSON unmarshaler to directly access and unmarshal the field. Here's the corrected struct definition:
<code class="go">Outer struct { I Inner // make Inner an explicit field Num int `json:"Num"` }</code>
In this updated version, the Inner field is made an explicit field named I. Additionally, the Num field is tagged with json:"Num" to ensure that the JSON key "Num" maps to this field during unmarshalling.
By adopting this approach, both the I and Num fields will be correctly populated when unmarshalling a JSON object into an instance of Outer.
The above is the detailed content of Why does JSON Unmarshaling of Embedded Structs Lead to Unexpected Behavior?. For more information, please follow other related articles on the PHP Chinese website!