Gravy
Gravy

Reputation: 12465

GoLang JSON Marshal omitempty with non-simple types - possible to avoid pointers?

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)
}

OUTPUT: {"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)
}

OUTPUT: {}

Upvotes: 0

Views: 846

Answers (1)

Volker
Volker

Reputation: 42478

Is there an alternative solution to this by not using pointers?

No.

Upvotes: 1

Related Questions