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
Release: 2024-11-26 14:56:08
Original
490 people have browsed it

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"`
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template