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

How to Handle Null Values When Parsing int64 JSON Data in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 15:38:14213browse

How to Handle Null Values When Parsing int64 JSON Data in Go?

JSON Parsing of int64 in Go: Handling Null Values

In Go, parsing JSON data containing integer values of type int64 can present challenges when encountering null values. When encountering null values, the default JSON package throws an error due to the inability to unmarshal null into an int64.

Nullable int64 Type for JSON Parsing

To overcome this limitation, a nullable int64 type is necessary. A nullable int64 allows for either a nil value or a valid int64 value. By using a pointer in Go, we achieve this functionality:

type NullableInt64 *int64

When using a pointer for the type, it can either be nil or reference an int64 value.

Implementation

Incorporating the nullable int64 type into the earlier example:

package main

import (
    "encoding/json"
    "fmt"
)

var d = []byte(`{ "world":[{"data": 2251799813685312}, {"data": null}]}`)

type jsonobj struct{ World []World }
type World struct{ Data *int64 } // Using *int64 for nullable int64

func main() {
    var data jsonobj
    jerr := json.Unmarshal(d, &data)
    fmt.Println(jerr)
}

This modification allows the JSON parser to successfully handle null values in the "data" field without encountering errors.

The above is the detailed content of How to Handle Null Values When Parsing int64 JSON Data 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