Marshal/unMarshal reflect.Type

huangapple go评论104阅读模式
英文:

Marshal/unMarshal reflect.Type

问题

我创建了一个map[string]interface{},并且我想在两个重置服务之间通过这个map传递多种类型的值。

每次我进行编组(marshal)时,我得到的字段中应该包含reflect.Type的map是空的。

ServiceType:map[]

这种情况是否可能?

用于测试的代码(KeyValuePair将表示map的单个值),MessageService可以替换为任何类型:

data := GenericHandlers.KeyValuePair{Key:"ServiceType",Value:reflect.TypeOf(MessageService.MessageService{})}
Json , _ := json.Marshal(data)
resKvp := GenericHandlers.KeyValuePair{}
err := json.Unmarshal(Json,&resKvp)
if(err != nil){
     log.Println(err.Error())
}
fmt.Println(resKvp)


type KeyValuePair struct{
        Key string
        Value interface{}
}
英文:

I created map[string]interface{} and i want to pass multiple types through the map between 2 reset services.

every time i marshal i get empty map in the field that should contain reflect.Type.

ServiceType:map[]

is it even possible?

code for testing: (the KeyValuePair will represent a single value of the map) and the MessageService can be replaced with any type of course

data := GenericHandlers.KeyValuePair{Key:"ServiceType",Value:reflect.TypeOf(MessageService.MessageService{})}
Json , _ := json.Marshal(data)
resKvp := GenericHandlers.KeyValuePair{}
err := json.Unmarshal(Json,&resKvp)
if(err != nil){
     log.Println(err.Error())
}
fmt.Println(resKvp)


type KeyValuePair struct{
        Key string
        Value interface{}
}

答案1

得分: 0

简短回答:不,这是不可能的。

稍微详细一点的回答:由于TypeOf返回的reflect.Type是一个由未导出的类型rtype实现的接口类型,它的字段都未导出,并且其方法集不包含MarshalJSON/UnmarshalJSON方法,因此你不能直接将reflect.Type值进行编组或解组。

英文:

Short answer: No, it's not possible.

Slightly longer answer: Since relfect.Type, as returned by TypeOf, is an interface type implemented by the unexported type rtype, none of whose fields are exported and whose method set does not contain the MarshalJSON/UnmarshalJSON methods, you cannot marshal or unmarshal a reflect.Type value as is.

huangapple
  • 本文由 发表于 2017年5月4日 05:58:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/43770692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定