Home >Backend Development >Golang >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:
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!