本文旨在解决 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) } } }
代码解释:
- *`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` 值。
运行结果:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
<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中文网其它相关文章!



