douqiao4450 2014-01-16 01:27
浏览 495
已采纳

无法将字符串解组为int64类型的Go值

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.

  • 写回答

2条回答 默认 最新

  • dongxing2263 2014-01-16 02:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名