【发布时间】:2019-12-29 15:24:25
【问题描述】:
我有一个包含 4 个字段的结构:
type Animal struct {
Name string
Age int
Zone int
}
我正在发送一个 json 对象以解码为结构的发布请求, json 应该如下所示:
{
"Age":10,
"Name":"Lion",
"Zone":1,
}
我希望所有字段都是字段,但我不会填写所有字段并发送一些 json 之类的。
{
"Age":10,
"Zone":1,
}
json.Decoder 自动构建该 Filed 并将其设置为 ""(该类型的值为零)而不是 null。
如何设置 null 值或检查它是否为 null 并生成错误?
我希望结果是{Age:10, Zone:1, Name:null} 或者至少会产生一个错误!
这是我用来将 json 转换为 struct 的代码
animalModel := Animal{}
err := json.NewDecoder(r.Body).Decode(&animalModel)
【问题讨论】: