Home > Backend Development > Golang > How Can I Distinguish Between JSON Null and Missing Fields When Unmarshaling in Go?

How Can I Distinguish Between JSON Null and Missing Fields When Unmarshaling in Go?

Mary-Kate Olsen
Release: 2024-12-03 21:03:17
Original
454 people have browsed it

How Can I Distinguish Between JSON Null and Missing Fields When Unmarshaling in Go?

Distinguishing JSON Fields Set to Null vs. Not Present During Unmarshaling

When unmarshaling JSON into a Golang struct, differentiation between fields set to null and fields that are not present can be crucial. Both scenarios result in nil values in the struct, obscuring the intended semantics.

Differentiation Using Generics (Go 1.18 )

Go 1.18 introduces generics, enabling a concise solution with a single generic type:

type Optional[T any] struct {
    Defined bool
    Value   *T
}
Copy after login

This type encapsulates the concept of an optional value with a defined field state (Defined).

Example Usage:

type Payload struct {
    Field1 Optional[string] `json:"field1"`
    Field2 Optional[int]   `json:"field2"`
}
Copy after login

After unmarshaling, fields with defined values (Defined == true) can distinguish between null values (Value == nil) and missing values (Defined == false).

Pre-Generics Solutions

Custom Type Wrapper:

type OptionalString struct {
    Defined bool
    Value   *string
}

func (os *OptionalString) UnmarshalJSON(data []byte) error {
    os.Defined = true
    return json.Unmarshal(data, &os.Value)
}
Copy after login

Example Usage:

type Payload struct {
    Field1 string         `json:"field1"`
    Field2 OptionalString `json:"field2"`
}
Copy after login

Limitations:

  • Requires a dedicated struct wrapper for each supported type (e.g., OptionalNumber for numeric types).
  • Does not provide a comprehensive distinction between null and missing values.

The above is the detailed content of How Can I Distinguish Between JSON Null and Missing Fields When Unmarshaling 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