在 golang 中使用反射将 json 转换为结构

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

}

调用它:

r,_:= deserialize(request,reflect.TypeOf(&testData{}))

它不会抛出错误并且在我看来是完全有效的操作,但结果是一个预期类型的​​空结构。

有什么问题吗?

问题是您正在传递类型的非指针实例:

payload:=reflect.New(v).Elem().Interface()

的意思是“分配一个新的指向该类型的指针,然后取它的值,并将其提取为interface{}

您应该将其保存在:

payload:=reflect.New(v).Interface()

顺便说一句,您传递指针的类型,提取其 Elem(),然后分配指针也是多余的。做这样的事情:

if type.Kind() == reflect.Ptr {
   typ = typ.Elem()
}

payload := reflect.New(typ).Interface()

那么你可以将指针和非指针都传递给函数。

编辑:工作操场示例:http://play.golang.org/p/TPafxcpIU5