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