英文:
Strict JSON parsing
问题
在使用Go解析JSON时,是否有可能在值为null或缺失时失败,而无需通过if语句检查每个字段?
例如:
package main
import (
"encoding/json"
"fmt"
)
type Bird struct {
Species string `json:"birdType"`
Description string `json:"what it does"`
}
func main() {
birdJson := `{"birdType": "pigeon"}`
var bird Bird
json.Unmarshal([]byte(birdJson), &bird)
fmt.Println(bird)
}
我期望会引发错误,因为"what it does"
未定义。
英文:
When parsing JSON with Go, is it possible to fail if a value is null or missing, without having to check every single field via an if statement?
For example:
package main
import (
"encoding/json"
"fmt"
)
type Bird struct {
Species string `json:"birdType"`
Description string `json:"what it does"`
}
func main() {
birdJson := `{"birdType": "pigeon"}`
var bird Bird
json.Unmarshal([]byte(birdJson), &bird)
fmt.Println(bird)
}
I'd expect to raise an error since "what it does"
is not defined
答案1
得分: 1
不,encoding/json.Unmarshal
如果目标结构体的字段在源 JSON 中没有匹配的对象键,将不会返回错误。
英文:
No, encoding/json.Unmarshal
will not return an error if the target struct has fields for which the source json does not contain any matching object keys.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论