Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot unmarshal string into Go value of type int64

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.

like image 737
Max Avatar asked Jan 16 '14 01:01

Max


2 Answers

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.

like image 88
Dmitri Goldring Avatar answered Sep 20 '22 10:09

Dmitri Goldring


use json.Number

type tySurvey struct {     Id     json.Number      `json:"id,omitempty"`     Name   string           `json:"name,omitempty"` } 
like image 43
YangXingf Avatar answered Sep 21 '22 10:09

YangXingf