Home > Backend Development > Golang > How to Unmarshal String-encoded Integers in Go?

How to Unmarshal String-encoded Integers in Go?

Barbara Streisand
Release: 2024-11-12 00:46:03
Original
1017 people have browsed it

How to Unmarshal String-encoded Integers in Go?

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

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!

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