Home  >  Article  >  Backend Development  >  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

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
DDDOriginal
2024-10-26 02:44:02325browse

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>

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>

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>

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!

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