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

Time:05-15

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

CodePudding user response:

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

  • Related