Home >Backend Development >Golang >How to Handle Null Integer Values When Unmarshalling JSON in Go?

How to Handle Null Integer Values When Unmarshalling JSON in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 10:12:12270browse

How to Handle Null Integer Values When Unmarshalling JSON in Go?

JSON Marshals Null Integer Values

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:

  • We define a pointer to int64 in the World struct (*int64) to allow nullable integers.
  • The jsonobj struct holds an array of World pointers, allowing it to handle both non-null and null integers.

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!

Statement:
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