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.

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

报告相同问题?

悬赏问题

  • ¥40 通过编制程序计算圆管内层流充分发展对流换热,参数如图5-4,以及公式5-16所示,要求用表5-6对程序计算准确性进行验证
  • ¥20 该学习哪个编程语言? AI会取代程序员吗?
  • ¥15 ensp如何拼通IP地址
  • ¥15 saber软件导入Ibis模型报错
  • ¥15 商城生产日期批次库存问题
  • ¥15 esp8266控制共阳极wrgb灯板无法关闭所有led灯
  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?