json parsing of int64 in go; null values

隐身守侯 提交于 2019-12-23 08:06:05

问题


I'm trying to parse a json stream in Go. 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.

Is there a nullable int64 type that json can handle? If possible I'd be happy with the json null being translated to, -1 or MinValue.

Thank you for your input, Fabian


回答1:


Just use a *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.



来源:https://stackoverflow.com/questions/10998222/json-parsing-of-int64-in-go-null-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!