Home  >  Article  >  Backend Development  >  Why is my `Num` field ignored when unmarshalling JSON to an embedded struct in Go?

Why is my `Num` field ignored when unmarshalling JSON to an embedded struct in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 15:03:42192browse

Why is my `Num` field ignored when unmarshalling JSON to an embedded struct in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn