Home > Backend Development > Golang > 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
Release: 2024-11-04 15:03:42
Original
261 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template