Deriving Custom Types for JSON Unmarshaling in Go
When working with custom types in Go, it's often necessary to implement the UnmarshalJSON function to enable automatic conversion from JSON to the desired type. However, challenges arise when the type is derived from a scalar value. This article explores a solution to overcome this issue.
Consider the example of a PersonID type that represents subtyped integer constants for identifying individuals. We want to extend this type's functionality to support automatic conversion from JSON strings. Implementing UnmarshalJSON for this type becomes difficult as it's intended to return or modify a scalar value directly, whereas UnmarshalJSON expects a struct for its modification.
To resolve this, we adopt a pointer receiver approach. By using a pointer receiver, changes made within the UnmarshalJSON method are reflected on the original value. Here's an example of the modified UnmarshalJSON implementation:
func (intValue *PersonID) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return err } *intValue = Lookup(s) return nil }
In this implementation, JSON text is unmarshaled into a string variable before being passed to the Lookup function, which converts the string to the desired PersonID value. This value is then assigned to the pointer intValue.
Additionally, to avoid conflicts between the JSON tags and the JSON data, ensure that the tags in the MyType struct match the field names in the JSON. By following these steps, you can successfully implement UnmarshalJSON for derived scalar types.
The above is the detailed content of How Can I Implement Custom JSON Unmarshaling for Derived Scalar Types in Go?. For more information, please follow other related articles on the PHP Chinese website!