'Ignoring an object in struct is nil and not when it's an empty array

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": []
}


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 twiny