Home > Backend Development > Golang > 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?

Patricia Arquette
Release: 2024-11-25 05:46:18
Original
408 people have browsed it

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template