【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
这样做的原因可以参考链接:
Golang 的 “omitempty” 关键字略解

上述修改后,反序列化的结果是:

{
	"width":256,
	"height":256,
	"size":1024
	"url":"wecode.fun/bucket/photo/a.jpg",
	"type":"JPG"
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值