"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Handle Embedded Structs with Custom UnmarshalJSON in Go?

How to Handle Embedded Structs with Custom UnmarshalJSON in Go?

Published on 2024-11-09
Browse:627

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:

type Outer struct {
    Inner
    Num int
}

type Inner struct {
    Data string
}

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

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:

type Outer struct {
    I Inner // make Inner an explicit field
    Num int `json:"Num"`
}

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

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
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3