How can I prevent JSON from being unmarshaled into a field of a struct?

a year ago by Lena to c/golang

Marshaling the field is fine, so using the tag json:"-" won't work. I could use the UnmarshalJSON method on the struct, but I have no idea how to implement it.

I'd rather not make a duplicate of the struct with that field removed, as it causes quite a bit of code duplication, and it's pretty chaotic.

pivot_root 2 points a year ago

One option is to use embedded structs:

type UnmarshalStruct struct {
    Foo string
}

type MarshalStruct struct {
    UnmarshalStruct
    FieldYouDontWantUnmarshaled string
}

When marshaling, you would marshal MarshalStruct. Because UnmarshalStruct is embedded, json.Marshal automatically includes all the fields from UnmarshalStruct.

When unmarshaling, you would unmarshal UnmarshalStruct and then create a new MarshalStruct like this:

var unmarshaled UnmarshalStruct
err := json.Unmarshal(&unmarshaled)
if err != nil {
    panic(err)
}

return MarshalStruct {
    UnmarshalStruct: unmarshaled
}

Although, if I may ask: why do you not want a field to be unmarshaled? You could always just set it back to the zero value after unmarshaling, which is a lot easier of a solution.

path: 0 18546172, hotness: undefined, score: 2, children: 0
golang
golang

@programming.dev

login for more options
2784
317
43

This is a community dedicated to the go programming language.

Useful Links:

Rules:

  • Posts must be relevant to Go
  • No NSFW content
  • No hate speech, bigotry, etc
  • Try to keep discussions on topic
  • No spam of tools/companies/advertisements
  • It’s OK to post your own stuff part of the time, but the primary use of the community should not be self-promotion.

go to feed...