Code below is the explanation. The only way I can get omitempty to work with non-simple types is to make that type a pointer.
Is there an alternative solution to this by not using pointers?
CODE NOT WORKING:
type Foo struct {
Bar Bar `json:"bar,omitempty"`
}
type Bar struct {
Baz string `json:"baz"`
}
func main() {
foo := Foo{}
jsonBytes, _ := json.Marshal(foo)
fmt.Printf("%s\n", jsonBytes)
}
{"bar":{"baz":""}}
CODE WORKING, BUT NOT WHAT I WANT:
type Foo struct {
Bar *Bar `json:"bar,omitempty"`
}
type Bar struct {
Baz string `json:"baz"`
}
func main() {
foo := Foo{}
jsonBytes, _ := json.Marshal(foo)
fmt.Printf("%s\n", jsonBytes)
}
{}