Home  >  Article  >  Backend Development  >  Why is the Num field ignored when unmarshalling JSON data into a struct containing an embedded struct?

Why is the Num field ignored when unmarshalling JSON data into a struct containing an embedded struct?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 21:18:02181browse

Why is the Num field ignored when unmarshalling JSON data into a struct containing an embedded struct?

Unmarshalling Embedded Structures in JSON

When attempting to unmarshal JSON data into a struct containing an embedded struct, certain challenges arise. Consider the following code:

<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>

Upon using json.Unmarshal(data, &Outer{}), the Num field is ignored. Why is this happening?

The issue stems from the embedding of Inner in Outer. When the JSON library calls UnmarshalJSON on Outer, it inadvertently calls it on Inner instead. Consequently, the data argument in func (i *Inner) UnmarshalJSON(data []byte) contains the entire JSON string, which is then processed only for Inner.

To resolve this issue, Inner needs to be an explicit field in Outer:

<code class="go">Outer struct {
    I Inner // make Inner an explicit field
    Num int `json:"Num"`
}</code>

Here's an example demonstrating the correct approach:

<code class="go">package main

import (
    "encoding/json"
    "fmt"
)

type Outer struct {
    I Inner `json:"I"`
    Num int `json:"Num"`
}

type Inner struct {
    Data string `json:"data"`
}

func (i *Inner) UnmarshalJSON(data []byte) error {
    i.Data = string(data)
    return nil
}

func main() {
    jsonStr := `{"I": "hello", "Num": 123}`
    var outer Outer
    err := json.Unmarshal([]byte(jsonStr), &outer)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(outer)
}</code>

The above is the detailed content of Why is the Num field ignored when unmarshalling JSON data into a struct containing an embedded struct?. 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