Home >Backend Development >Golang >How to Unmarshal JSON Strings into Int64 Go Values?

How to Unmarshal JSON Strings into Int64 Go Values?

Barbara Streisand
Barbara StreisandOriginal
2024-11-14 17:16:02544browse

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.

The above is the detailed content of How to Unmarshal JSON Strings into Int64 Go Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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