Home >Backend Development >Golang >How to Handle Embedded Structs with Custom UnmarshalJSON in Go?
In Go, when unmarshaling JSON data into a struct with embedded fields, one may encounter issues if the embedded struct defines its own UnmarshalJSON method. This is because the JSON library calls the embedded struct's UnmarshalJSON and ignores the fields defined in the containing struct.
Consider the following struct definition:
<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>
When unmarshaling JSON into Outer using json.Unmarshal(data, &Outer{}), the Inner field triggers its UnmarshalJSON method, consuming the entire JSON string. This causes the Num field in Outer to be ignored.
To resolve this issue, convert the embedded struct Inner to an explicit field in Outer:
<code class="go">type Outer struct { I Inner // make Inner an explicit field Num int `json:"Num"` }</code>
By making Inner an explicit field, you ensure that the JSON library unmarshals the data into the appropriate fields of Outer, including the Num field.
<code class="go">import ( "encoding/json" "fmt" ) type Outer struct { I Inner // make Inner an explicit field Num int `json:"Num"` } type Inner struct { Data string } func (i *Inner) UnmarshalJSON(data []byte) error { i.Data = string(data) return nil } func main() { data := []byte(`{"Data": "Example", "Num": 42}`) var outer Outer err := json.Unmarshal(data, &outer) if err != nil { fmt.Println(err) } fmt.Println(outer.I.Data, outer.Num) // Output: Example 42 }</code>
The above is the detailed content of How to Handle Embedded Structs with Custom UnmarshalJSON in Go?. For more information, please follow other related articles on the PHP Chinese website!