Home > Backend Development > Golang > How to Handle Null Values When Parsing JSON int64s in Go?

How to Handle Null Values When Parsing JSON int64s in Go?

Linda Hamilton
Release: 2024-11-28 14:56:11
Original
159 people have browsed it

How to Handle Null Values When Parsing JSON int64s in Go?

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
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template