"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 Can I Implement Custom JSON Unmarshaling for Derived Scalar Types in Go?

How Can I Implement Custom JSON Unmarshaling for Derived Scalar Types in Go?

Published on 2024-11-19
Browse:636

How Can I Implement Custom JSON Unmarshaling for Derived Scalar Types in Go?

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.

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