gpt4 book ai didi

json - 为什么在接口(interface)中添加 func 会导致 json.Unmarshal 失败?

转载 作者:IT王子 更新时间:2023-10-29 01:52:05 28 4
gpt4 key购买 nike

为什么会失败并出现错误:

json: cannot unmarshal object into Go struct field Person.spouse of type main.Spouse

type Spouse interface {
Name() // Adding this causes an error
}

type Address interface {
}

type Person struct {
Name string `json:"name"`
A *Address `json:"address"`
S *Spouse `json:"spouse"`
}

func main() {
b := []byte(`{
"name":"sarah",
"address":{
"street":"101 main"
},
"spouse":{
"name":"joe"
}
}
`)

p := &Person{}
if err := json.Unmarshal(b, p); err != nil {
fmt.Printf("%s", err)
}
}

查看 docs ,我不明白为什么在接口(interface)中添加函数会导致错误。我原以为 json.Unmarshal 会简单地忽略 Name() 函数,因为它不是 list 的一部分由 json.Unmarshal 处理。

这是go playground中的代码.

go版本go1.10 darwin/amd64

最佳答案

来自fine manual :

func Unmarshal
[...]
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

您正在尝试将一个 JSON 对象解码到一个接口(interface)中,因此该接口(interface)后面的值将是一个 map[string]interface{}。来表示键/值对。但是map[string]interface{}没有 Name()方法,因此它不会实现您的 Spouse界面。

如果我们稍微简化您的示例并去掉 Name()我们可以看到发生了什么的方法:

type Spouse interface {
}

type Person struct {
S *Spouse `json:"spouse"`
}

func main() {
b := []byte(`{"spouse":{ "name":"joe" } }`)

p := &Person{}
if err := json.Unmarshal(b, p); err != nil {
fmt.Printf("%s", err)
}
spouse := (*p.S).(map[string]interface{})
fmt.Printf("%+v\n", spouse)
}

spousemap[string]interface{}如文件所示。

关于json - 为什么在接口(interface)中添加 func 会导致 json.Unmarshal 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49440537/

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