Go json omitempty如何實現(xiàn)可選屬性
更新時間:2024年09月17日 09:38:03 作者:wecode66
在Go語言中,使用`omitempty`可以幫助我們在進行JSON序列化和反序列化時,忽略結構體中的零值或空值,本文介紹了如何通過將字段類型改為指針類型,并在結構體的JSON標簽中添加`omitempty`來實現(xiàn)這一功能,例如,將float32修改為*float32
Go json omitempty實現(xiàn)可選屬性
有以下 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" }
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Go語言模型:string的底層數(shù)據(jù)結構與高效操作詳解
這篇文章主要介紹了Go語言模型:string的底層數(shù)據(jù)結構與高效操作詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12