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)
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