Go json omitempty如何實(shí)現(xiàn)可選屬性
更新時(shí)間:2024年09月17日 09:38:03 作者:wecode66
在Go語言中,使用`omitempty`可以幫助我們?cè)谶M(jìn)行JSON序列化和反序列化時(shí),忽略結(jié)構(gòu)體中的零值或空值,本文介紹了如何通過將字段類型改為指針類型,并在結(jié)構(gòu)體的JSON標(biāo)簽中添加`omitempty`來實(shí)現(xiàn)這一功能,例如,將float32修改為*float32
Go json omitempty實(shí)現(xiàn)可選屬性
有以下 json 字符串
{ "width":256, "height":256, "size":1024 "url":"wecode.fun/bucket/photo/a.jpg", "type":"JPG" }
對(duì)應(yīng) go 的結(jié)構(gòu)體
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 結(jié)構(gòu)是
{ "width":256, "height":256, "size":1024 "url":"wecode.fun/bucket/photo/a.jpg", "type":"JPG", "duration":0.0 }
這里的 “duration”:0.0 并不是我們需要的。
要去掉這個(gè),可以借助 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個(gè)改動(dòng):
- 1、duration 添加了 omitempty
- 2、float32 修改為 指針類型 *float32
這樣做的原因可以參考鏈接:
Golang 的 “omitempty” 關(guān)鍵字略解
上述修改后,反序列化的結(jié)果是:
{ "width":256, "height":256, "size":1024 "url":"wecode.fun/bucket/photo/a.jpg", "type":"JPG" }
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Go語言模型:string的底層數(shù)據(jù)結(jié)構(gòu)與高效操作詳解
這篇文章主要介紹了Go語言模型:string的底層數(shù)據(jù)結(jié)構(gòu)與高效操作詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12Go語言并發(fā)之context標(biāo)準(zhǔn)庫的使用詳解
Context的出現(xiàn)是為了解決在大型應(yīng)用程序中的并發(fā)環(huán)境下,協(xié)調(diào)和管理多個(gè)goroutine之間的通信、超時(shí)和取消操作的問題,本文就來和大家簡(jiǎn)單聊聊它的具體用法,希望對(duì)大家有所幫助2023-06-06