Home >Backend Development >Golang >How to Resolve 'Cannot Unmarshal String into Go Value of Type Int64' JSON Parsing Error?

How to Resolve 'Cannot Unmarshal String into Go Value of Type Int64' JSON Parsing Error?

Linda Hamilton
Linda HamiltonOriginal
2024-11-26 14:56:08503browse

How to Resolve

JSON Parsing Error: "Cannot Unmarshal String into Go Value of Type Int64"

Issue:
When attempting to unmarshal JSON data with a string value assigned to an int64 field, the unmarshaling process fails due to a type mismatch between the source string and the expected integer value.

Problem Details:
A custom Go struct defines an int64 field using JSON struct tags to map it to a JSON property. However, a jQuery script modifies the JSON object and encodes it as a string rather than an integer. This leads to a string being sent in place of the expected int64 value.

Solution:
To handle this type conversion issue, add the ",string" tag to the relevant field. The updated struct tag is as follows:

type tySurvey struct {
   Id   int64  `json:"id,string,omitempty"`
   Name string `json:"name,omitempty"`
}

By specifying ",string" in the JSON struct tag, the unmarshaling process will recognize that the field value can be a string and will attempt to convert it to an integer before assigning it to the int64 field.

Additional Note:
It's important to note that if the string value is the empty string, it cannot be decoded because the omitempty option is only used during encoding.

The above is the detailed content of How to Resolve 'Cannot Unmarshal String into Go Value of Type Int64' JSON Parsing Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn