"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Unmarshal String-encoded Integers in Go?

How to Unmarshal String-encoded Integers in Go?

Published on 2024-11-12
Browse:492

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"`
}

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.

Latest tutorial More>

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