简体   繁体   中英

How do I serialize a map of type [string]reflect.Value?

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())
}

(ie 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM