无法将字符串解组为类型为int64的Go值 [英] Cannot unmarshal string into Go value of type int64

查看:1596
本文介绍了无法将字符串解组为类型为int64的Go值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有struct

 类型t​​ySurvey结构{
Id int64`json:id,omitempty`
名称字符串`json:name,omitempty`
}

我做 json.Marshal 在HTML页面中写入JSON字节。 jQuery修改对象中的 name 字段,并使用jQueries JSON.stringify 编码对象,jQuery将字符串发布到Go处理程序。



id 编码为字符串的字段。

已发送: {id:1} 收到: {id:1}

b

问题在于 json.Unmarshal 无法解组该JSON,因为 id 不是整数

  json:不能将字符串解组为类型为int64的Go值

处理这些数据的最佳方法是什么?我不希望手动转换每个字段。我希望编写紧凑的,无缺陷的代码。



行情并不太糟糕。 JavaScript不能很好地处理int64。



我想要学习使用int64值解析json字符串值的简单方法。

解决方案

这是通过向您的标记添加,string 来处理的,如下所示:

 类型t​​ySurvey结构{
Id int64`json:id,string,omitempty`
名称字符串`json:name,omitempty `
}

这可以在元帅



请注意,您不能通过指定 omitempty 来解码空字符串,因为它仅在编码时使用。


I have struct

type tySurvey struct {
    Id     int64            `json:"id,omitempty"`
    Name   string           `json:"name,omitempty"`
}

I do json.Marshal write JSON bytes in HTML page. jQuery modifies name field in object and encodes object using jQueries JSON.stringify and jQuery posts string to Go handler.

id field encoded as string.

Sent: {"id":1} Received: {"id":"1"}

Problem is that json.Unmarshal fails to unmarshal that JSON because id is not integer anymore.

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.

I would like to learn the easy way to unmarshal json with string values in int64 values.

解决方案

This is handled by adding ,string to your tag as follows:

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.

Please note that you cannot decode the empty string by specifying omitempty as it is only used when encoding.

这篇关于无法将字符串解组为类型为int64的Go值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆