解组到自定义界面

时间:2018-10-12 16:47:40

标签: json go

通常的解组方法是这样的:

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

如何正确执行?

1 个答案:

答案 0 :(得分:3)

要解组为一组都实现一个公共接口的类型,可以在父类型上实现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
}

有关完整示例,请参见this playground。确保您解组到CustomInterfaceMap,而不是map[string]CustomInterface,否则将不会调用自定义UnmarshalJSON方法。

json.RawMessage是有用的类型,它只是原始的JSON编码值,这意味着它是一个简单的[]byte,JSON以未解析的形式存储在其中。