go json omitempty实现可选属性
有以下 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
这样做的原因可以参考链接:
上述修改后,反序列化的结果是:
{ "width":256, "height":256, "size":1024 "url":"wecode.fun/bucket/photo/a.jpg", "type":"jpg" }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论