"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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

Published on 2024-11-08
Browse:942

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:

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

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

var ping interface{} = &Ping{}
deserialize([]byte(`{"id":42}`), ping)
fmt.Println("DONE:", ping)

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

var ping interface{} = Ping{}
nptr := reflect.New(reflect.TypeOf(ping))
deserialize([]byte(`{"id":42}`), nptr.Interface())
ping = nptr.Interface()
fmt.Println("DONE:", ping)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3