为了账号安全,请及时绑定邮箱和手机立即绑定

解组到自定义接口

解组到自定义接口

Go
LEATH 2023-04-24 15:54:26
通常的解组方法是这样的: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 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

要解组为一组类型,它们都实现一个公共接口,您可以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 值,这意味着它是一个简单的[]byteJSON 以未解析的形式存储在其中。


查看完整回答
反对 回复 2023-04-24
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信