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
Mary-Kate OlsenOriginal
2024-12-03 21:03:17401browse

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
}

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"`
}

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)
}

Example Usage:

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

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!

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