json - Go JSON 解码错误行为是如何工作的?
问题描述
当遇到错误时,我试图了解 Go 中 JSON 解码和解组的行为。特别是,在以下结构中,该title
字段的格式与返回的 JSON 提供的格式不同,并提供了一个错误。尽管出现错误,行为是否会继续处理其他字段,还是会停止处理其他字段?我还没有提到标准库中如何处理这个问题。
type Response struct {
Title struct {
Text string `json:"text"`
Accessibility struct {
Label string `json:"label"`
Identifier string `json:"identifier"`
} `json:"accessibility"`
} `json:"title,omitempty"`
Type string `json:"type"`
}
{
"title": "test",
"type": "type"
}
解决方案
快速测试揭示了这一点:
func main() {
var r Response
if err := json.Unmarshal([]byte(src), &r); err != nil {
fmt.Println(err)
}
fmt.Printf("%+v", r)
}
const src = `{
"title": "test",
"type": "type"
}
结果(在Go Playground上尝试):
json: cannot unmarshal string into Go struct field Response.title of type struct { Text string "json:\"text\""; Accessibility struct { Label string "json:\"label\""; Identifier string "json:\"identifier\"" } "json:\"accessibility\"" }
{Title:{Text: Accessibility:{Label: Identifier:}} Type:type}
在后续字段正确解组时返回非nil
错误。Type
一般来说:返回一个错误,而解组继续没有任何保证。
这记录在json.Unmarshal()
:
如果 JSON 值不适合给定的目标类型,或者 JSON 编号溢出目标类型,Unmarshal 会跳过该字段并尽其所能完成解组。如果没有遇到更严重的错误,Unmarshal 返回一个 UnmarshalTypeError描述最早的此类错误。在任何情况下,都不能保证有问题的字段后面的所有剩余字段都将被解组到目标对象中。