The omitempty tag parameter omitempty not work with time.Time , since it is a struct . There is a “null” value for structs, but this is a structure value, where all fields have null values. This is a "real" value, therefore it is not considered as "empty".
But just changing it to a pointer: *time.Time , it will work ( nil pointers are considered as "empty" for json marshaling / unmarshaling). Therefore, there is no need to write a custom Marshaler in this case:
type MyStruct struct { Timestamp *time.Time `json:",omitempty"` Date *time.Time `json:",omitempty"` Field string `json:",omitempty"` }
Using it:
ts := time.Date(2015, 9, 18, 0, 0, 0, 0, time.UTC) ms := MyStruct{ Timestamp: &ts, Field: "", }
Output (optional):
{"Timestamp":"2015-09-18T00:00:00Z"}
Try it on the go playground .
If you cannot or do not want to change it to a pointer, you can still achieve what you want by doing Marshaler and Unmarshaler . If you do, you can use the Time.IsZero() method to decide if time.Time null value.
icza Sep 18 '15 at 7:17 2015-09-18 07:17
source share