Go programmers often encounter the error message "json: cannot unmarshal string into Go value of type int64" when attempting to Unmarshal JSON data. This error occurs when the JSON field corresponding to an int64-typed Go struct field contains a string value.
Consider the following Go struct:
type Survey struct { Id int64 `json:"id,omitempty"` Name string `json:"name,omitempty"` }
If you Marshal this struct into JSON and modify the "id" field in a JavaScript client, it may send a JSON string like this:
{"id": "1"}
where the "id" field is now a string.
When you attempt to Unmarshal this JSON string into the Go struct, you will encounter the aforementioned error.
To handle this situation, you can specify the ,string option in your JSON tag, as seen below:
type Survey struct { Id int64 `json:"id,string,omitempty"` Name string `json:"name,omitempty"` }
This allows the "id" field to be unmarshaled as an int64 even if the JSON value is a string.
It's important to note that specifying omitEmpty for string-tagged fields only affects the marshaling process, not the unmarshaling process. This means that you cannot unmarshal an empty string into an int64 field, even if it is tagged with ,string,omitempty.
以上是如何將 JSON 字串解組為 Int64 Go 值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!