Home >Backend Development >Golang >How Can I Differentiate Between Null and Absent JSON Fields in Go?

How Can I Differentiate Between Null and Absent JSON Fields in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 13:24:12238browse

How Can I Differentiate Between Null and Absent JSON Fields in Go?

Differentiating Null from Absent JSON Fields in Go

In Go, when unmarshalling JSON data into a struct, both null fields and absent fields result in nil values in the resulting struct. This can be a challenge when it's essential to distinguish between the two scenarios, such as when a field being null signifies specific intent versus its absence indicating it was never present.

Utilizing Optional Structs (Go 1.18 )

For Go 1.18 and later, generics allow for a straightforward solution using a custom struct: Optional[T]. This struct incorporates a Defined boolean field, which indicates the field's presence in the JSON payload, and a Value field, which contains the actual value. When unmarshalling, if the value is defined (not null), UnmarshalJSON is invoked, setting the Defined and Value fields appropriately.

type Optional[T any] struct {
    Defined bool
    Value   *T
}
type Payload struct {
    Field1 Optional[string] `json:"field1"`
    Field2 Optional[bool]   `json:"field2"`
    Field3 Optional[int32]  `json:"field3"`
}

By checking the Defined field, you can discern if a field was null or undefined.

Custom Unmarshaler with Pre-Generics

Prior to Go 1.18, a custom Unmarshaler can be used for this purpose:

type OptionalString struct {
    Defined bool
    Value   *string
}

func (os *OptionalString) UnmarshalJSON(data []byte) error {
    // UnmarshalJSON is called only if the key is present
    os.Defined = true
    return json.Unmarshal(data, &os.Value)
}
type Payload struct {
    SomeField1 string         `json:"somefield1"`
    SomeField2 OptionalString `json:"somefield2"`
}

In this approach, the OptionalString struct implements the json.Unmarshaler interface, setting Defined to true when the field is present in the JSON payload. This allows for differentiation between fields that are null and those that are absent.

The above is the detailed content of How Can I Differentiate Between Null and Absent JSON Fields 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