有以下 json 字符串
{
"width":256,
"height":256,
"size":1024
"url":"wecode.fun/bucket/photo/a.jpg",
"type":"JPG"
}
对应 go 的结构体
type MediaSummary struct {
Width int `json:"width"`
Height int `json:"height"`
Size int `json:"size"`
URL string `json:"url"`
Type string `json:"type"`
Duration float32 `json:"duration"`
}
反序列化后,得到的 json 结构是
{
"width":256,
"height":256,
"size":1024
"url":"wecode.fun/bucket/photo/a.jpg",
"type":"JPG",
"duration":0.0
}
这里的 “duration”:0.0 并不是我们需要的。
要去掉这个,可以借助 omitempty 属性。即:
type MediaSummary struct {
Width int `json:"width"`
Height int `json:"height"`
Size int `json:"size"`
URL string `json:"url"`
Type string `json:"type"`
Duration *float32 `json:"duration,omitempty"`
}
注意,上述有定义2个改动:
1、duration 添加了 omitempty
2、float32 修改为 指针类型 *float32
这样做的原因可以参考链接:
Golang 的 “omitempty” 关键字略解
上述修改后,反序列化的结果是:
{
"width":256,
"height":256,
"size":1024
"url":"wecode.fun/bucket/photo/a.jpg",
"type":"JPG"
}
本文探讨了在Go语言中如何处理JSON反序列化时遇到的冗余字段问题,通过在结构体字段上使用`omitempty`标签以及将字段类型改为指针,可以避免在JSON对象中出现不需要的默认值。具体案例中,`duration`字段在反序列化后由于其值为0.0而被自动忽略,确保了输出的JSON结构符合预期。
941

被折叠的 条评论
为什么被折叠?



