Home >Backend Development >Golang >How to Handle Embedded Structs with Custom UnmarshalJSON in Go?

How to Handle Embedded Structs with Custom UnmarshalJSON in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 14:29:02216browse

How to Handle Embedded Structs with Custom UnmarshalJSON in Go?

Error Handling: Custom Unmarshal for Embedded Structs

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.

Case Study

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.

Solution: Explicit Field

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.

Example

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

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