Home >Backend Development >Golang >How to Prevent Stack Overflow Errors When Using json.Unmarshal within UnmarshalJSON?

How to Prevent Stack Overflow Errors When Using json.Unmarshal within UnmarshalJSON?

Susan Sarandon
Susan SarandonOriginal
2024-12-19 18:36:10942browse

How to Prevent Stack Overflow Errors When Using json.Unmarshal within UnmarshalJSON?

Avoiding Stack Overflow when Calling json.Unmarshal in UnmarshalJSON

Calling json.Unmarshal(b, type) within your custom UnmarshalJSON implementation can lead to a stack overflow error. This occurs because the JSON decoder repeatedly attempts to find a custom UnmarshalJSON implementation for the type, resulting in an infinite loop.

Solution: Create a New Type

To avoid this issue, create a new type using the type keyword. This new type will not inherit the methods of the original type, including UnmarshalJSON.

type person2 Person

Usage:

Convert the original type's value to the new type using a type conversion:

if err := json.Unmarshal(data, (*person2)(p)); err != nil {
    return err
}

Example:

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func (p *Person) UnmarshalJSON(data []byte) error {
    type person2 Person
    if err := json.Unmarshal(data, (*person2)(p)); err != nil {
        return err
    }
    // Custom processing
    if p.Age < 0 {
        p.Age = 0
    }
    return nil
}

Benefits:

  • Prevents stack overflows
  • Incurs no runtime overhead since the underlying representation remains unchanged

The above is the detailed content of How to Prevent Stack Overflow Errors When Using json.Unmarshal within UnmarshalJSON?. 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