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 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题