Home > Backend Development > Golang > How Can I Unmarshal JSON Strings into Custom Go Scalar Types?

How Can I Unmarshal JSON Strings into Custom Go Scalar Types?

Barbara Streisand
Release: 2024-12-02 13:08:16
Original
752 people have browsed it

How Can I Unmarshal JSON Strings into Custom Go Scalar Types?

Unmarshalling JSON Values into Derived Scalar Types in Go

Problem

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.

Solution

To address this, follow these steps:

  1. Use a pointer receiver for the unmarshal method. This allows changes made within the method to be reflected in the original value.
  2. Unmarshal the JSON text to a plain string. Remove any JSON quotes or escape sequences.
  3. Use the derived type's method to convert the string to the desired value. In this case, call the Lookup method to obtain the PersonID value.

Example

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

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.

Conclusion

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!

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