Home > Backend Development > Golang > How to Unmarshal JSON Strings into Custom Go Types Derived from Scalar Values?

How to Unmarshal JSON Strings into Custom Go Types Derived from Scalar Values?

Barbara Streisand
Release: 2024-11-19 12:54:02
Original
354 people have browsed it

How to Unmarshal JSON Strings into Custom Go Types Derived from Scalar Values?

How Can JSON Unmarshal Handle Value Types Derived from Scalars in Go?

In Go, scalar values are often used to represent simple data types like integers and strings. Custom types derived from these scalar values may require special handling during JSON unmarshaling to ensure accurate mapping.

Problem Statement

Implement the UnmarshalJSON method for a custom type that extends a scalar integer in Go. The goal is to automatically convert incoming JSON strings into values of this custom type.

Solution

To overcome the limitations of UnmarshalJSON expecting a struct, utilize the following steps:

  1. Use a Pointer Receiver: Employ a pointer receiver for the UnmarshalJSON method. Value receivers lose changes upon method return.
  2. Unmarshal JSON Text: Unmarshal the JSON text to obtain a plain string, removing any JSON quoting.
  3. Lookup and Assign: Utilize the Lookup function to retrieve an instance of the custom type based on the parsed string. Assign this value to the pointer receiver.

Example 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

Additional Considerations

  • Ensure consistency between JSON tags and the JSON data being unmarshaled.
  • Use pointers to avoid losing changes made during unmarshaling.
  • Consider a custom MarshalJSON method if you want to customize JSON serialization.

With these techniques implemented, you can effectively unmarshal JSON strings into your custom types derived from scalar values in Go.

The above is the detailed content of How to Unmarshal JSON Strings into Custom Go Types Derived from Scalar Values?. 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