
本文旨在解决 Go 语言中使用 encoding/json 包解析 JSON 数据时,遇到的 Int64 类型字段为 null 值的问题。通过使用 *int64 指针类型,可以有效地处理 JSON 中的 null 值,并提供了一种简单的方法来避免 json: cannot unmarshal null into Go value of type int64 错误。
在 Go 语言中使用 encoding/json 包解析 JSON 数据时,如果 JSON 中某个字段的值为 null,而 Go 结构体中对应的字段类型为 int64,则会抛出 json: cannot unmarshal null into Go value of type int64 错误。这是因为 int64 是一个值类型,不能直接赋值为 null。
为了解决这个问题,可以使用 *int64 指针类型。指针类型可以为 nil,因此可以用来表示 JSON 中的 null 值。
示例代码:
package main
import (
"encoding/json"
"fmt"
)
var d = []byte(`{ "world":[{"data": 2251799813685312}, {"data": null}]}`)
type jsonobj struct {
World []World
}
type World struct {
Data *int64 `json:"data"` // 使用 *int64
}
func main() {
var data jsonobj
jerr := json.Unmarshal(d, &data)
fmt.Println(jerr)
fmt.Println(data)
// 遍历 World 数组,检查 Data 的值
for _, w := range data.World {
if w.Data == nil {
fmt.Println("Data is null")
} else {
fmt.Printf("Data is: %d\n", *w.Data)
}
}
}代码解释:
运行结果:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
<nil>
{[{2251799813685312} {<nil>}]}
Data is: 2251799813685312
Data is null可以看到,程序成功解析了 JSON 数据,并且能够正确处理 null 值。
注意事项:
总结:
通过使用 *int64 指针类型,可以有效地处理 Go 语言中使用 encoding/json 包解析 JSON 数据时,遇到的 Int64 类型字段为 null 值的问题。 这种方法简单易用,并且能够保证程序的健壮性。在处理包含 null 值的 JSON 数据时,建议使用指针类型来表示可能为 null 的字段。
以上就是JSON 解析 Go 中 Int64 类型的 Null 值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号