英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论