Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
JSON 解析 Go 中 Int64 类型的 Null 值_创想鸟

JSON 解析 Go 中 Int64 类型的 Null 值

json 解析 go 中 int64 类型的 null 值

本文旨在解决 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 mainimport (    "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: %dn", *w.Data)        }    }}

代码解释:

*`Data int64 `json:”data”`**: 将World结构体中的Data字段类型从int64修改为int64。int64表示指向int64` 类型的指针。json:”data”: JSON 标签,用于指定 JSON 字段名。if w.Data == nil: 在遍历 World 数组时,使用 w.Data == nil 判断 Data 字段是否为 null。*`fmt.Printf(“Data is: %dn”, w.Data)**: 如果Data字段不为null,则使用*w.Data获取指针指向的int64` 值。

运行结果:

{[{2251799813685312} {}]}Data is: 2251799813685312Data is null

可以看到,程序成功解析了 JSON 数据,并且能够正确处理 null 值。

注意事项:

使用 *int64 后,需要注意对指针进行判空操作,避免空指针异常。如果需要将 null 值转换为其他值,可以在解析后进行处理。例如,可以将 null 值转换为 -1 或 MinValue。

总结:

通过使用 *int64 指针类型,可以有效地处理 Go 语言中使用 encoding/json 包解析 JSON 数据时,遇到的 Int64 类型字段为 null 值的问题。 这种方法简单易用,并且能够保证程序的健壮性。在处理包含 null 值的 JSON 数据时,建议使用指针类型来表示可能为 null 的字段。

以上就是JSON 解析 Go 中 Int64 类型的 Null 值的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1403832.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Golang反射调用性能优化与替代方案
上一篇 2025年12月15日 19:55:39
优化函数式语言虚拟机:实用技巧与策略
下一篇 2025年12月15日 19:55:49

相关推荐

发表回复

登录后才能评论
关注微信