我有一个声明方法的接口和一些实现该接口的结构。现在我想将一些 JSON 解组到这些结构的实例中。以机智:
package main
import (
"encoding/json"
"fmt"
)
type Animal interface {
makeNoise() string
}
type Dog struct {
Name string
}
func (d Dog) makeNoise() string {
return "woof"
}
type Fish struct {
NumScales int
}
func (f Fish) makeNoise() string {
return "glub glub glub"
}
type Zoo struct {
Animals []Animal
}
func main() {
animals := `{"Animals": [{"Name": "Fido"}, {"NumScales": 123}]}`
animalBytes := []byte(animals)
var zoo Zoo
er := json.Unmarshal(animalBytes, &zoo)
if er != nil {
panic(er)
} else {
fmt.Println(zoo)
}
}
但是当我运行它时,我得到“panic: json: cannot unmarshal object into Go value of type main.Animal”。我可以换一个动物园,它的动物是一只名叫 Fido 的狗和一条 123 鳞片的鱼吗?
繁星coding
Qyouu
相关分类