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
Release: 2024-11-28 10:12:12
Original
244 people have browsed it

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

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

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

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!

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