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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3