如何序列化[string] reflect.Value类型的映射? [英] How do I serialize a map of type [string]reflect.Value?

查看:190
本文介绍了如何序列化[string] reflect.Value类型的映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力寻找如何使它工作的方法,但是我陷入了困境.

我有一个看起来像这样的对象:

type PropSet map[string]*Prop

type Prop struct {
    val reflect.Value
}

,我需要生成它所保存的所有键值对的JSON表示形式.我一直在阅读SO上有关如何封送更多普通类型的文章,但我一直无法弄清楚如何处理reflect.Value类型.我想我应该可以做这样简单的事情:

func (p Prop) MarshalJSON() ([]byte, error) {
    return json.Marshal(p.val.Value().Interface())
}

...但是它不起作用.有什么建议吗?

补充说明:我没有写数据结构,但是我认为它使用了reflect.Value作为映射值的原因是我们期望的值可以是int,float,string等.本质上,这需要对基本接口进行某种类型的推断,以得出返回结果.

解决方案

您快到了:reflect.Value本身没有Value接收器方法,也不需要.将您的MarshalJSON实现更改为以下工作:

 func (p Prop) MarshalJSON() ([]byte, error) {
    return json.Marshal(p.val.Interface())
}
 

(即从函数调用链中删除.Value()).

游乐场链接

(我不喜欢在这里使用reflect –依赖反射的解决方案很少清晰易懂,但似乎除了选择不使用它之外,您无法更改上游数据结构.)

I have been trying to work out how to get this to work, and I am stuck.

I have an object that looks like this:

type PropSet map[string]*Prop

type Prop struct {
    val reflect.Value
}

and I need to generate a JSON representation of all the key value pairs that it holds. I have been reading posts on SO talking about how to marshal more mundane types, but I have not been able to figure out how to deal with the reflect.Value type. I think I should be able to do something simple like this:

func (p Prop) MarshalJSON() ([]byte, error) {
    return json.Marshal(p.val.Value().Interface())
}

... but it just isn't working. Any suggestions?

Additional note: I didn't write the data structure, but the reason that I think it is using the reflect.Value for the map value is that the values that we are expecting can be ints, floats, strings etc. So this is essentially needs to do some sort of type inference with base interface to figure out the return result.

解决方案

You're almost there: reflect.Value doesn't itself have a Value receiver method, nor does it need one. Changing your MarshalJSON implementation to the following works:

func (p Prop) MarshalJSON() ([]byte, error) {
    return json.Marshal(p.val.Interface())
}

(i.e. dropping .Value() from the chain of function calls).

Playground link

(I don't like the use of reflect here – solutions relying on reflection are rarely clear and understandable, but it seems you can't change the upstream data structure, besides choosing not to use it.)

这篇关于如何序列化[string] reflect.Value类型的映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆