json - 忽略 struct 中的对象是 nil 而不是当它是一个空数组时

是否可以仅在对象为 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":[]}

运行上面的例子:https://goplay.tools/snippet/J_iKIJ9ZMhT

相似文章

go - Gorm - 预加载尽可能深

我正在使用Gorm,并且对如何从模型中检索嵌套的SubComments有一些疑问。我遇到的问题是嵌套两层的评论,即Comment.SubComments没有加载。我错过了Preload的内容吗?我还认...

随机推荐

最新文章