Home >Backend Development >Golang >How to Correctly MarshalJSON() When Embedding Structs with Custom MarshalJSON() Methods?
Embedding a Struct with Custom MarshalJSON()
When embedding a struct with a custom MarshalJSON() method, the outer struct's fields are promoted to the promoted type, overriding the embedded struct's MarshalJSON() method. This can lead to unexpected results when marshalling the outer struct.
Problem:
Consider the following structs:
type Person struct { Name string `json:"name"` } func (p *Person) MarshalJSON() ([]byte, error) { return json.Marshal(struct { Name string `json:"name"` }{ Name: strings.ToUpper(p.Name), }) } type Employee struct { *Person JobRole string `json:"jobRole"` }
Marshalling an Employee instance produces unexpected results:
p := Person{"Bob"} e := Employee{&p, "Sales"} output, _ := json.Marshal(e) fmt.Printf("%s\n", string(output))
Output:
{"name": "BOB"}
The jobRole field is missing, despite being set on the Employee instance.
Solution:
Option 1: Avoid MarshalJSON() on Embedded Type
Option 2: Implement MarshalJSON() on Outer Type
Note: Both options require some manual handling and may affect the ordering of fields in the final JSON output.
The above is the detailed content of How to Correctly MarshalJSON() When Embedding Structs with Custom MarshalJSON() Methods?. For more information, please follow other related articles on the PHP Chinese website!