是否可以僅在物件為 nil 而不是空陣列時使用 omitempty?
我希望 JSON 編組器在物件為 nil 時不顯示值,但object: []在值為空串列時顯示。
objects: nil
{
...
}
objects: make([]*Object, 0)
{
...
"objects": []
}
uj5u.com熱心網友回復:
您將需要為您的結構創建一個自定義的 json Marshal/Unmarshal 函式。就像是:
// Hello
type Hello struct {
World []interface{} `json:"world,omitempty"`
}
// MarshalJSON()
func (h *Hello) MarshalJSON() ([]byte, error) {
var hello = &struct {
World []interface{} `json:"world"`
}{
World: h.World,
}
return json.Marshal(hello)
}
// UnmarshalJSON()
func (h *Hello) UnmarshalJSON(b []byte) error {
var hello = &struct {
World []interface{} `json:"world"`
}{
World: h.World,
}
return json.Unmarshal(b, &hello)
}
輸出:
{"world":[]}
運行上面的例子:https ://goplay.tools/snippet/J_iKIJ9ZMhT
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474691.html
上一篇:Golang列印結構總是報未定義
