首页 > 解决方案 > 严格的 JSON 解析

问题描述

使用 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"未定义

标签: jsongo

解决方案


不,encoding/json.Unmarshal如果目标结构具有源 json 不包含任何匹配对象键的字段,则不会返回错误。


推荐阅读