【发布时间】:2014-07-24 21:30:57
【问题描述】:
我有一个带有interface{} 类型字段的结构。在使用 memcached (https://github.com/bradfitz/gomemcache) 对其进行缓存的过程中,该结构被编组为 JSON,然后在从缓存中检索时将其解组回该结构。生成的interface{} 字段不可避免地指向类型为 map[string]interface{} 的对象(如interface{} 字段只能类型断言为 map[string]interface{}),编组和解组过程没有保留类型信息。有没有办法在编组过程中保存这些信息,以便可以正确解组?还是我必须使用其他编解码器或其他东西?
type A struct {
value interface{}
}
type B struct {
name string
id string
}
func main() {
a := A{value: B{name: "hi", id: "12345"}}
cache.Set("a", a) // Marshals 'a' into JSON and stores in cache
result = cache.Get("a") // Retrieves 'a' from cache and unmarshals
fmt.Printf("%s", result.value.(B).name) // Generates error saying that
// map[string]interface{} cannot be type asserted as a 'B' struct
fmt.Printf("%s", result.value.(map[string]interface{})["name"].(string)) // Correctly prints "12345"
}
【问题讨论】:
-
标题应该是:Unmarshalling JSON into Go interface{}?
-
是的,我就是这个意思