gpt4 book ai didi

json - 解码到自定义接口(interface)

转载 作者:IT王子 更新时间:2023-10-29 01:56:45 24 4
gpt4 key购买 nike

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

atmosphereMap := make(map[string]interface{})
err := json.Unmarshal(bytes, &atmosphereMap)

但是如何将 json 数据解码到自定义接口(interface):

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

如何正确操作?

最佳答案

要解码为一组类型,它们都实现了一个公共(public)接口(interface),您可以实现 json.Unmarshaler父类型上的接口(interface),在您的情况下为 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 以未解析的形式存储在其中。

关于json - 解码到自定义接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52783848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com