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!