Handling String Input for Int64 Fields in JSON Unmarshaling
Unmarshaling JSON data into Go values can occasionally encounter challenges, particularly when encountering string representations of integral values. This article explores a solution to the error "json: cannot unmarshal string into Go value of type int64" when unmarshaling JSON data with string-encoded integral fields.
Problem Statement
Consider the following Go struct representing a survey response:
type tySurvey struct { Id int64 `json:"id,omitempty"` Name string `json:"name,omitempty"` }
In this example, the id field is defined as int64. After serializing tySurvey to JSON and transmitting it for client-side manipulation, the client updates the name field. However, it inadvertently encodes the id field as a string during data transmission.
Upon receiving the modified JSON data on the server, the original tySurvey struct is unmarshaled, resulting in an error: "json: cannot unmarshal string into Go value of type int64."
Solution
The solution lies in modifying the JSON field tags by appending ,string to the type definition. This instructs the json unmarshaler to accept string representations for integral values:
type tySurvey struct { Id int64 `json:"id,string,omitempty"` Name string `json:"name,omitempty"` }
The ,string option allows for seamless conversion of string-encoded integral values into corresponding Go values during unmarshaling.
Additional Considerations
When specifying ,omitempty for string-encoded integral values, it's crucial to note that the empty string cannot be decoded. This limitation ensures that omitempty is only utilized during encoding.
Conclusion
Appending ,string to the JSON field tags enables effortless unmarshaling of string-encoded integral values in Go. This technique simplifies data handling and enhances code robustness by accommodating client-side data manipulations that may inadvertently alter field types.
Atas ialah kandungan terperinci Bagaimana untuk Mengendalikan Input Rentetan untuk Medan Int64 dalam JSON Unmarshaling?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!