In Go, unmarshalling JSON values into custom scalar types can be challenging due to the inability to modify the scalar value within the UnmarshalJSON method. This issue arises when implementing UnmarshalJSON for types derived from scalars, preventing the automatic conversion of strings in JSON to values of the derived type.
To address this, follow these steps:
Here's a corrected implementation of the UnmarshalJSON method for PersonID:
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 }
Additionally, ensure that the JSON tag in the MyType struct matches the field name in the example JSON. If necessary, update json: "person" to match the JSON tag used in the example.
By following these steps, you can implement UnmarshalJSON for derived scalar types, enabling the automatic conversion of JSON strings to the desired value type. This allows for effortless parsing of JSON data into custom types.
The above is the detailed content of How Can I Unmarshal JSON Strings into Custom Go Scalar Types?. For more information, please follow other related articles on the PHP Chinese website!