Join GitHub today
GitHub is home to over 36 million developers working together to host and review code, manage projects, and build software together.Sign up
encoding/json: calls UnmarshalJSON with a nil receiver on anonymous fields #17877
Please answer these questions before submitting your issue. Thanks!
What version of Go are you using (
changed the title
encoding/json: Doesn't Unmarshal anonymous field with custom unmarshaler
Nov 16, 2016
My understanding is that this is working as intended. In the first case, Outer is a Marshaler, so Unmarshal will call its custom UnmarshalJSON on it directly. While in other cases, Outer is not a Marshaler. The default behavior for Unmarshal is documented as:
Yes, @shantuo is right. From the json package's point of view, it allocates an Outer, sees that Outer has an UnmarshalJSON method (due to the embedding), and invokes Outer's UnmarshalJSON method. The raison d'être of UnmarshalJSON is to stop the usual processing, and in this case, that means not looking inside Outer at all. The json package cannot be responsible for allocating the inner struct.
Other ways to write this code include embedding a struct instead of a pointer-to-struct.