Convert json to struct using reflection in golang -
func deserialize(request *http.request,typ reflect.type) (interface{}, *httpnet.handlererror){ data,e:=ioutil.readall(request.body) fmt.println(string(data)) if e !=nil{ return nil,&httpnet.handlererror{e,"could not read request",http.statusbadrequest} } v:=typ.elem() payload:=reflect.new(v).elem().interface() eaa:= json.newdecoder(request.body).decode(payload) if e!=nil{ fmt.println(eaa.error()) } fmt.println(payload) fmt.println(reflect.valueof(payload) ) return payload,nil }
to call it:
r,_:= deserialize(request,reflect.typeof(&testdata{}))
it not throw errors , looks valid operation me , result empty structure of expecting type.
whats problem that?
the problem passing non pointer instance of type:
payload:=reflect.new(v).elem().interface()
means "allocate new pointer type, take value of it, , extract interface{}
.
you should keep at:
payload:=reflect.new(v).interface()
btw it's redundant passing type of pointer, extracting elem()
, allocating pointer. this:
if type.kind() == reflect.ptr { typ = typ.elem() } payload := reflect.new(typ).interface()
then can pass both pointers , non pointers function.
edit: working playground example: http://play.golang.org/p/tpafxcpiu5
Comments
Post a Comment