Home  >  Article  >  Backend Development  >  How to Unmarshal JSON Strings into Custom Go Scalar Types?

How to Unmarshal JSON Strings into Custom Go Scalar Types?

Susan Sarandon
Susan SarandonOriginal
2024-11-21 12:58:10317browse

How to Unmarshal JSON Strings into Custom Go Scalar Types?

Unmarshaling JSON Strings to Derived Scalar Types in Go

In Go, you can derive a new scalar type from an existing one. However, implementing UnmarshalJSON for such types can be challenging due to limitations in the standard library.

To correctly handle this, it is essential to use a pointer receiver for the UnmarshalJSON method. Value receivers do not retain changes made within the method.

The argument passed to UnmarshalJSON is JSON text. This can be unmarshalled into a plain string, discarding any quoting.

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 tags in your code match the keys in the JSON data you are unmarshalling.

json.Unmarshal([]byte(`{"person": "Ralph", "count": 4, "greeting": "Hello"}`), &m);

By following these steps, you can effectively implement UnmarshalJSON for derived scalar types, enabling automatic conversion of JSON strings to values of your custom type.

The above is the detailed content of How to Unmarshal JSON Strings into Custom Go Scalar Types?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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