JSON Parsing of int64s: Handling Null Values in Go
When parsing JSON streams in Go, handling null values can be a challenge, especially when dealing with int64 types. As demonstrated in the example provided, attempting to unmarshal a JSON object containing a null value into a struct field of type int64 will result in an error due to the type mismatch.
Using a Pointer to Address Null Values
A straightforward solution to this issue is to use a pointer to int64. A pointer can be nil, representing a null value, or it can point to a valid int64 instance with an associated value. This approach is supported by Go's JSON package.
type World struct { Data *int64 }
By modifying the struct definition above to use a pointer to int64, we can now successfully unmarshal the JSON data without encountering the previous error. The *int64 allows the JSON parser to represent null values as nil pointers.
Mapping null to Non-Null Values
If desired, you can map the null values to a non-null value, such as -1 or MinValue. This can be achieved by custom processing the JSON data after unmarshaling. For example:
func MapNull(data *int64) int64 { if data == nil { return -1 } return *data }
By invoking the MapNull function after unmarshaling, you can replace any null values with the desired non-null representation.
Conclusion
Handling null values when parsing JSON data containing int64 types in Go can be achieved by employing a pointer to int64. This technique allows the JSON parser to represent null values and preserves the original data structure. If necessary, custom post-processing can be applied to map null values to alternative non-null representations.
The above is the detailed content of How to Handle Null Values When Parsing JSON int64s in Go?. For more information, please follow other related articles on the PHP Chinese website!