JSON custom marshaller and `omitempty` option

If I put json:",omitempty" after a field, (for example a string) if the string is empty, the result is not contain the field.
But I have a custom type with custom MarshalJSON function. the problem is, How i can tell the json library that this value is empty?

something like this (this not work, I get the : “json: error calling MarshalJSON for type main.Custom: unexpected end of JSON input” when the Show is false)

type Custom struct {
    Name string
    Show bool
}

type FinalJSON struct {
    T1 Custom `json:"field,omitempty"`
    T2 string    `json:"field2,omitempty"
}

func (c *Custom) MarshalJSON() ([]byte, error) {

	if !c.Show {
		return nil, nil
	}

	return json.Marshal(c.Name)
}

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

I believe your Custom field need to be a pointer then passing a nil to *Custom will make it being omitted.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.