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:
type Outer struct {
Inner
Num int
}
type Inner struct {
Data string
}
func (i *Inner) UnmarshalJSON(data []byte) error {
i.Data = string(data)
return nil
}
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:
type Outer struct {
I Inner // make Inner an explicit field
Num int `json:"Num"`
}
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.
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
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3