dongmangwei3822 2018-10-24 13:16
浏览 65
已采纳

是否可以动态设置json.Unmarshal的输出?

I have the following Go code:

var typeRegistry = make(map[string]reflect.Type)

func init() {
    typeRegistry["User"] = reflect.TypeOf(User{})
}

func makeInstance(name string) interface{} {
    v := reflect.New(typeRegistry[name]).Elem()
    return v.Interface()
}

func Invoke(any interface{}, name string, body []byte, signature Signature) {
    args := signature.Args
    data := makeInstance(signature.Args[0])
    json.Unmarshal(body, &data)
    inputs := make([]reflect.Value, len(args))
    for i, _ := range signature.Args {
        log.Println(reflect.TypeOf(data))
        log.Println(reflect.ValueOf(data))
        inputs[i] = reflect.ValueOf(data)
    }
    reflect.ValueOf(any).MethodByName(name).Call(inputs)
}

I'm attempting to pass in some JSON, and a string denoting what type the JSON should be mapped to. I'm attempting to use reflection to mush the two together again and pass it into a method by the methods name.

I kind of got it working, however, when I use a pointer un json.Unmarshal it seems to lose the reference to its assigned type again, and defaults back to map[string]interface{} which is a mis-match for the method I'm calling. In this case it's expecting type main.User. If I remove the pointer from json.Unmarshal(body, data) the types match correctly, but obviously the data is no longer being set for data.

I'm aware I'm bastardising Go's type-system, and probably using the language in ways that isn't suggested, but I'm trying to do something more academic than useful, I guess.

  • 写回答

1条回答 默认 最新

  • duanchi6377 2018-10-24 13:28
    关注

    You have to pass a pointer to json.Unmarshal(), else it can't change the (pointed) data, only a copy of it. This is what happens when you pass data: since it can't change the value (non-pointer value of type User wrapped in interface{}), therefore it creates a new value it can unmarshal into. And it will choose whatever it sees fit bests (but it won't be User but rather map[string]interface{} as you experienced).

    So yes, you have to pass a pointer to it, but &data will not be what you want. &data will be a pointer to interface, of type *interface{} because makeInstance() returns a value of interface{} type, so data will have that inferred type.

    The solution is to change makeInstance() to return a pointer which may be wrapped in an interface{} value, that's ok. And then you may simply pass data to json.Unmarshal(), because the data interface value will hold a value of type *User.

    So do:

    func makeInstance(name string) interface{} {
        v := reflect.New(typeRegistry[name]) // Don't call Elem() here
        return v.Interface()
    }
    

    And in Invoke():

    data := makeInstance(signature.Args[0])
    json.Unmarshal(body, data)
    

    See related question that was posted just a few hours ago:

    Store information/reference about structure

    You can see a working demo here: Go Playground.

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

报告相同问题?

悬赏问题

  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误