Differentiating Null and Non-Existent JSON Fields in Go
When unmarshalling JSON into Go structs, it can be challenging to distinguish between JSON fields that are explicitly set to null and those that are simply not present in the JSON payload. This distinction is crucial in many scenarios, as it affects the semantics of the data and its interpretation.
Go 1.18 Solution
Starting with Go 1.18, a generic Optional struct can be utilized to address this issue:
type Optional[T any] struct { Defined bool Value *T }
This struct implements the UnmarshalJSON interface, allowing it to distinguish defined and undefined values. When unmarshalling a JSON payload, the defined field of the Optional struct will be set to true, regardless of whether the value is null or a valid value.
Example Usage
type Payload struct { Field1 Optional[string] `json:"field1"` Field2 Optional[bool] `json:"field2"` Field3 Optional[int32] `json:"field3"` }
After unmarshalling a JSON payload, the Defined field can be used to determine if a specific field was present in the JSON or not.
Pre-Go 1.18 Solution
For versions of Go prior to 1.18, a custom type can be created to achieve the same result.
type OptionalString struct { Defined bool Value *string }
Similar to the Optional struct in Go 1.18 , this type implements the UnmarshalJSON interface to set the Defined field accordingly.
Example Usage
type Payload struct { SomeField1 string `json:"somefield1"` SomeField2 OptionalString `json:"somefield2"` }
By utilizing this custom type, the Defined field can be inspected to differentiate between null and non-existent fields.
The above is the detailed content of How Can I Differentiate Between Null and Missing JSON Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!