JSON 解析 Go 中 Int64 类型的 Null 值

2025-10-31 0 172

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 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: %dn", *w.Data)         }     } }
登录后复制

代码解释:

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

运行结果:

JSON 解析 Go 中 Int64 类型的 Null 值

Find JSON Path Online

Easily find JSON paths within JSON objects using our intuitive Json Path Finder

Find JSON Path Online30

查看详情 Find JSON Path Online

<nil> {[{2251799813685312} {<nil>}]} Data is: 2251799813685312 Data is null
登录后复制

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

注意事项:

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

总结:

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

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

遇见资源网 后端开发 JSON 解析 Go 中 Int64 类型的 Null 值 https://www.ox520.com/1094.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务