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

无法将字符串解组为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.

我有结构 p>

  type tySurvey结构{
 ID  int64`json:“ id,omitempty”`
名称字符串`json:“ name,omitempty”`
} 
  code>  pre> 
 
 

我执行 json。 元帅 code>在HTML页面中写入JSON字节。 jQuery修改对象中的 name code>字段,并使用jQueries JSON.stringify code>对对象进行编码,然后jQuery将字符串发布到Go处理程序。 p>

id code>字段编码为字符串。 p>

已发送: {“ id”:1} code>收到: {“ id”:“ 1” } code> p>

问题在于 json.Unmarshal code>无法解组该JSON,因为 id code>不再是整数了。 p>

  json:无法将字符串解组为int64 
  code>  pre> 
 
 

类型的Go值是什么? 我不希望手动转换每个字段。 我希望编写紧凑,无错误的代码。 p>

行情还不错。 JavaScript不适用于int64。 p>

我想学习一种简单的方法来将int64值中的字符串值解组json。 p> div>

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.

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

Let's fix this.

Your case is -> http post 'localhost:8080/users/blahblah' id=1

Change it to -> http post 'localhost:8080/users/blahblah' id:=1

No need to do "json:id,string" thing, Just "json:id" is enough. Good luck!