The challenge arises when an embedded struct defines a customized MarshalJSON() method, causing unexpected JSON serialization behavior when attempting to marshal the containing struct.
Consider the following struct definitions:
1 2 3 4 5 6 7 8 |
|
Marshaling the Employee struct as expected is straightforward:
1 2 3 4 |
|
Output:
1 |
|
However, defining a custom MarshalJSON() method for the embedded struct, as shown below, disrupts the intended serialization:
1 2 3 4 5 6 7 |
|
Now, marshaling the Employee produces output with the name field converted to uppercase but misses the jobRole field:
1 |
|
To maintain the desired serialization behavior, avoid defining a MarshalJSON() method on the embedded struct (Person). Instead, create a separate type encapsulating the custom marshalling logic and embed that type:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
This approach isolates the marshalling customization to a dedicated type, preventing unexpected side effects when embedding the Person struct elsewhere.
Example: https://play.golang.org/p/u96T4C6PaY
The above is the detailed content of How to Idiomatically Embed a Struct with a Custom `MarshalJSON()` in Go?. For more information, please follow other related articles on the PHP Chinese website!