简体   繁体   English

go中int64的json解析; 空值

[英]json parsing of int64 in go; null values

I'm trying to parse a json stream in Go.我正在尝试在 Go 中解析 json 流。 I've created a simplified 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 }

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

this will give me这会给我

go run testmin.go
json: cannot unmarshal null into Go value of type int64

I've found a nullable int64 in the sql package , but json doesn't seem to be able to handle it.我在sql 包中发现了一个可为空的 int64,但 json 似乎无法处理它。

Is there a nullable int64 type that json can handle?是否有 json 可以处理的可为空的 int64 类型? If possible I'd be happy with the json null being translated to, -1 or MinValue.如果可能,我会很高兴将 json null转换为 -1 或 MinValue。

Thank you for your input, Fabian感谢您的投入,法比安

Just use a *int64 .只需使用*int64 A pointer can either be nil or it can point to an int64 with an associated value and they work fine with Go's JSON package.指针可以是 nil,也可以指向具有关联值的 int64,它们与 Go 的 JSON 包一起工作得很好。

https://github.com/guregu/null包含 null.Int null.String 等以及相应的 JSON 序列化/反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM