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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵