encoding/json: custom MarshalJSON() on anonymous field blocks encoding of sibling struct fields #39915
Comments
This seems like a dupe of #39175. |
It seems like the same root issue. Your method is being promoted to the main type, so it's being used to marshal the entire parent type, not just the embedded one. This is how methods in Go work. |
That explains it. Thanks. |
For the next person with this problem: you can embed a 2nd struct implementing a custom MarshalJSON(), and sibling fields will encode again. I made a dummy struct just for this purpose: type JSON_Hack int
func (V JSON_Hack) MarshalJSON() ([]byte, error) {
return []byte("null"), nil
}
type Example struct {
Embed1WithCustomMarshaller
JSON_Hack `json:"-"`
Sibling1 int
Sibling2 string
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
When I JSON encode a struct that embeds another struct (ICustom) as an anonymous field, and that struct (ICustom) implements MarshalJSON(), only ICustom is encoded, and other fields are omitted.
When I do the same thing, but where the embedded struct doesn't implement MarshalJSON(), all fields are included.
See: https://play.golang.org/p/VKH--_G432v
What did you expect to see?
The same output for both, given the code in the example.
What did you see instead?
Sibling fields omitted.
The text was updated successfully, but these errors were encountered: