dongyuelian9602 2015-06-14 10:25
浏览 181
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • doujiyan0971 2015-06-14 10:31
    关注

    The problem is that you are passing a non pointer instance of the type:

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

    Means "allocate a new pointer to the type, then take the value of it, and extract it as interface{}.

    You should just keep it at:

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

    BTW It's also redundant that you are passing the type of a pointer, extracting its Elem(), then allocating a pointer. Do something like this:

    if type.Kind() == reflect.Ptr {
       typ = typ.Elem()
    }
    
    payload := reflect.New(typ).Interface()
    

    then you can pass both pointers and non pointers to the function.

    Edit: Working playground example: http://play.golang.org/p/TPafxcpIU5

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器