Here are a few title options, keeping in mind the need for a question format: * **Why Does `json.Unmarshal` Return a Map Instead of a Struct in Go?** (Simple and direct) * **Golang: Unmarshaling int

DDD
Release: 2024-10-26 02:44:02
Original
324 people have browsed it

Here are a few title options, keeping in mind the need for a question format:

* **Why Does `json.Unmarshal` Return a Map Instead of a  Struct in Go?** (Simple and direct)
* **Golang: Unmarshaling into an Interface - Why is My Struct a Map?** (More specif

Why Does json.Unmarshal Return a Map Instead of the Expected Struct?

In this playground example, json.Unmarshal returns a map instead of the expected struct: http://play.golang.org/p/dWku6SPqj5.

The issue arises because an interface{} parameter is passed to json.Unmarshal, and the library attempts to unmarshal it into a byte array. However, the library doesn't have a direct reference to the corresponding struct, even though it has a reflect.Type reference.

The problem lies in the following code:

<code class="go">var ping interface{} = Ping{}
deserialize([]byte(`{"id":42}`), &ping)
fmt.Println("DONE:", ping) // It's a simple map now, not a Ping. Why?</code>
Copy after login

To resolve this issue, either pass a pointer to the Ping struct explicitly as an abstract interface:

<code class="go">var ping interface{} = &Ping{}
deserialize([]byte(`{"id":42}`), ping)
fmt.Println("DONE:", ping)</code>
Copy after login

Alternatively, if a direct pointer is unavailable, create a new pointer using reflect, deserialize into it, and then copy the value back:

<code class="go">var ping interface{} = Ping{}
nptr := reflect.New(reflect.TypeOf(ping))
deserialize([]byte(`{"id":42}`), nptr.Interface())
ping = nptr.Interface()
fmt.Println("DONE:", ping)</code>
Copy after login

The above is the detailed content of Here are a few title options, keeping in mind the need for a question format: * **Why Does `json.Unmarshal` Return a Map Instead of a Struct in Go?** (Simple and direct) * **Golang: Unmarshaling int. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!