解编组的通常方法如下:
atmosphereMap := make(map[string]interface{})
err := json.Unmarshal(bytes, &atmosphereMap)但是如何将json数据解编组到自定义接口:
type CustomInterface interface {
G() float64
}
atmosphereMap := make(map[string]CustomInterface)
err := json.Unmarshal(bytes, &atmosphereMap)第二种方法给了我一个错误:
panic: json: cannot unmarshal object into Go value of type main.CustomInterface怎样才能做好呢?
发布于 2018-10-12 17:38:45
要将其解封为一组类型(所有这些类型都实现了一个公共接口),您可以在父类型上实现json.Unmarshaler接口,在您的示例中实现map[string]CustomInterface:
type CustomInterfaceMap map[string]CustomInterface
func (m CustomInterfaceMap) UnmarshalJSON(b []byte) error {
data := make(map[string]json.RawMessage)
if err := json.Unmarshal(b, &data); err != nil {
return err
}
for k, v := range data {
var dst CustomInterface
// populate dst with an instance of the actual type you want to unmarshal into
if _, err := strconv.Atoi(string(v)); err == nil {
dst = &CustomImplementationInt{} // notice the dereference
} else {
dst = &CustomImplementationFloat{}
}
if err := json.Unmarshal(v, dst); err != nil {
return err
}
m[k] = dst
}
return nil
}有关完整的示例,请参见这个操场。确保您将封送处理解压缩为CustomInterfaceMap,而不是map[string]CustomInterface,否则将不会调用自定义UnmarshalJSON方法。
json.RawMessage是一个有用的类型,它只是一个原始编码的JSON值,这意味着它是一个简单的[]byte,其中JSON以未解析的形式存储。
https://stackoverflow.com/questions/52783848
复制相似问题