Unmarshalling String-encoded Integers in Go
When attempting to unmarshal JSON with string values into an integer field, one may encounter the error: "json: cannot unmarshal string into Go value of type int64." This is because JSON unmarshaling by default assumes numeric types, such as int64, should contain numerical characters.
Issue:
A Go struct defining an int64 field is receiving JSON with the corresponding field encoded as a string. This mismatch in data types causes the unmarshaling process to fail.
Solution:
The recommended solution is to use the ",string" tag in the json struct tag for the integer field. This instructs the unmarshaling process to accept values of type string:
type tySurvey struct { Id int64 `json:"id,string,omitempty"` Name string `json:"name,omitempty"` }
Implementation:
With the modified struct, JSON data with an id field encoded as a string can now be successfully unmarshaled into a Go object of type tySurvey.
Note:
It's important to remember that specifying omitempty in the tag will not allow for the empty string to be decoded. omitempty is used exclusively for encoding purposes.
The above is the detailed content of How to Unmarshal String-encoded Integers in Go?. For more information, please follow other related articles on the PHP Chinese website!