How to Handle Embedded Structs with Custom UnmarshalJSON in Go?

Barbara Streisand
Release: 2024-11-04 14:29:02
Original
205 people have browsed it

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

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

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

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!

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