json 无法将字符串解组为 int64 类型的 Go 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21151765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot unmarshal string into Go value of type int64
提问by Max
I have struct
我有结构
type tySurvey struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
I do json.Marshalwrite JSON bytes in HTML page. jQuery modifies namefield in object and encodes object using jQueries JSON.stringifyand jQuery posts string to Go handler.
我确实json.Marshal在 HTML 页面中编写了 JSON 字节。jQuery 修改name对象中的字段并使用 jQueries 对对象进行编码JSON.stringify,jQuery 将字符串发布到 Go 处理程序。
idfield encoded as string.
id字段编码为字符串。
Sent: {"id":1}Received: {"id":"1"}
发送:{"id":1}接收:{"id":"1"}
Problem is that json.Unmarshalfails to unmarshal that JSON because idis not integer anymore.
问题是json.Unmarshal无法解组该 JSON,因为id它不再是整数。
json: cannot unmarshal string into Go value of type int64
What is best way to handle such data? I do not wish to manually convert every field. I wish to write compact, bug free code.
处理此类数据的最佳方法是什么?我不想手动转换每个字段。我希望编写紧凑、无错误的代码。
Quotes is not too bad. JavaScript does not work well with int64.
行情还不错。JavaScript 不适用于 int64。
I would like to learn the easy way to unmarshal json with string values in int64 values.
我想学习使用 int64 值中的字符串值解组 json 的简单方法。
回答by Dmitri Goldring
This is handled by adding ,stringto your tag as follows:
这是通过添加,string到您的标签来处理的,如下所示:
type tySurvey struct {
Id int64 `json:"id,string,omitempty"`
Name string `json:"name,omitempty"`
}
This can be found about halfway through the documentation for Marshal.
这可以在Marshal的文档中找到。
Please note that you cannot decode the empty string by specifying omitemptyas it is only used when encoding.
请注意,您不能通过指定来解码空字符串,omitempty因为它仅在编码时使用。
回答by KaungMyatChanThar
Sent: {"id":1} Received: {"id":"1"}
Let's fix this.
让我们解决这个问题。
Your case is -> http post 'localhost:8080/users/blahblah' id=1
你的情况是 -> http post 'localhost:8080/users/blahblah' id=1
Change it to ->
http post 'localhost:8080/users/blahblah' id:=1
将其更改为->
http post 'localhost:8080/users/blahblah' id:=1
No need to do "json:id,string"thing, Just "json:id"is enough.
Good luck!
不需要做任何"json:id,string"事情,就"json:id"足够了。祝你好运!

