忽略struct中的对象是零,而不是一个空数组

发布于 2025-01-29 09:19:32 字数 320 浏览 4 评论 0原文

当对象为零而不是空数阵列时,是否可以使用省略时才使用OmitEmpty?

我希望JSON MARSHALLER在对象为零时不显示该值,而是要显示对象:[]当值为空列表时。

objects: nil

{
  ...
}
objects: make([]*Object, 0)

{
  ...
  "objects": []
}

Is it possible to only use omitempty when an object is nil and not when it's an empty array?

I would like for the JSON marshaller to not display the value when an object is nil, but show object: [] when the value is an empty list.

objects: nil

{
  ...
}
objects: make([]*Object, 0)

{
  ...
  "objects": []
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

难理解 2025-02-05 09:19:33
    t := []string{}
    json, _ := json.Marshal(struct {
        Data *[]string `json:"data,omitempty"`
    }{Data: &t})
    fmt.Println(string(json)) // Output: {"data":[]}

https://go.dev/play/play/p/zpi39iou-p5

    t := []string{}
    json, _ := json.Marshal(struct {
        Data *[]string `json:"data,omitempty"`
    }{Data: &t})
    fmt.Println(string(json)) // Output: {"data":[]}

https://go.dev/play/p/ZPI39ioU-p5

谁人与我共长歌 2025-02-05 09:19:32

您将需要为您的结构创建自定义的JSON元帅/Unmarshal功能。 something like:

// 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)
}

Output:

{"world":[]}

Run above example: https://goplay.tools/snippet/J_iKIJ9ZMhT

You will need to create a custom json Marshal/Unmarshal functions for your struct. something like:

// 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)
}

Output:

{"world":[]}

Run above example: https://goplay.tools/snippet/J_iKIJ9ZMhT

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文