In Go, parsing JSON streams can sometimes lead to complications, especially when dealing with integers and null values. Let's explore a common issue and its resolution using nullable types.
Problem:
When parsing JSON data containing integers, you may encounter the following error:
json: cannot unmarshal null into Go value of type int64
This error occurs when you have nullable integers in the JSON, which the standard Go JSON package cannot handle directly.
Solution:
To address this issue, consider using pointers to integers. A pointer can be either nil (representing a null value) or it can point to an integer with an associated value. Here's how to implement it:
import ( "encoding/json" "fmt" ) var d = []byte(`{ "world":[{"data": 2251799813685312}, {"data": null}]}`) type jsonobj struct{ World []*int64 } type World struct{ Data *int64 } func main() { var data jsonobj jerr := json.Unmarshal(d, &data) if jerr != nil { fmt.Println(jerr) } for _, w := range data.World { if w == nil { fmt.Println("Got a null value") } else { fmt.Println(*w) } } }
In this modified example:
When parsing the JSON, it correctly handles numeric and null integer values and prints them accordingly:
Got a null value 2251799813685312
This approach provides a simple and effective way to handle nullable integers in Go when parsing JSON streams.
The above is the detailed content of How to Handle Null Integer Values When Unmarshalling JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!