首頁  >  文章  >  後端開發  >  如何將 JSON 字串解組為 Int64 Go 值?

如何將 JSON 字串解組為 Int64 Go 值?

Barbara Streisand
Barbara Streisand原創
2024-11-14 17:16:02441瀏覽

How to Unmarshal JSON Strings into Int64 Go Values?

Unmarshaling JSON Strings into Int64 Go Values

Go programmers often encounter the error message "json: cannot unmarshal string into Go value of type int64" when attempting to Unmarshal JSON data. This error occurs when the JSON field corresponding to an int64-typed Go struct field contains a string value.

Problem Overview

Consider the following Go struct:

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

If you Marshal this struct into JSON and modify the "id" field in a JavaScript client, it may send a JSON string like this:

{"id": "1"}

where the "id" field is now a string.

When you attempt to Unmarshal this JSON string into the Go struct, you will encounter the aforementioned error.

Solution

To handle this situation, you can specify the ,string option in your JSON tag, as seen below:

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

This allows the "id" field to be unmarshaled as an int64 even if the JSON value is a string.

Note

It's important to note that specifying omitEmpty for string-tagged fields only affects the marshaling process, not the unmarshaling process. This means that you cannot unmarshal an empty string into an int64 field, even if it is tagged with ,string,omitempty.

以上是如何將 JSON 字串解組為 Int64 Go 值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn