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

无法将字符串解组为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 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题