go - Unmarshal json to reflected struct -
is possible unmarshal json struct made reflection without hardcoding original type?
package main import ( "fmt" "encoding/json" "reflect" ) type employee struct { firstname string `json:"firstname"` } func main() { //original struct orig := new(employee) t := reflect.typeof(orig) v := reflect.new(t.elem()) //reflected struct new := v.elem().interface().(employee) // unmarshal reflected struct json.unmarshal([]byte("{\"firstname\": \"bender\"}"), &new) fmt.printf("%+v\n", new) }
i used cast employee
in example. if don't know type?
when use v
unmarhaling struct zeroed.
json.unmarshal([]byte("{\"firstname\": \"bender\"}"), v)
when omit cast map. understandable
json.unmarshal([]byte("{\"firstname\": \"bender\"}"), v.elem().interface())
the problem here if omit type assertion here:
new := v.elem().interface()
the new
inferred have interface{}
type.
then when take address unmarshal, type of &new
*interface{}
(pointer interface{}) , unmarshal not work expect.
you can avoid type assertion if instead of getting elem()
work directly pointer reference.
func main() { //original struct orig := new(employee) t := reflect.typeof(orig) v := reflect.new(t.elem()) // reflected pointer newp := v.interface() // unmarshal reflected struct pointer json.unmarshal([]byte("{\"firstname\": \"bender\"}"), newp) fmt.printf("%+v\n", newp) }
playground: https://play.golang.org/p/ltbu-1pqm4
Comments
Post a Comment