是否可以仅在对象为 nil 而不是空数组时使用 omitempty?
我希望 JSON 编组器在对象为 nil 时不显示 value,但在 value 为空列表时显示 object: []
。
objects: nil
{
...
}
objects: make([]*Object, 0)
{
...
"objects": []
}
回答1
你需要为你的 struct 创建一个自定义的 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":[]}