dimanche 14 juin 2015

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 does not throw errors and looks completely valid operation to me , but the result is an empty structure of expecting type.

Whats the problem with that?





Aucun commentaire:

Enregistrer un commentaire