Given the following structs:
type Person {
Name string `json:\"name\"`
}
type Employee {
Person
JobRole string `json:\"jobRole\"`
}
<
I've used this approach on parent structs to keep the embedded struct from overriding marshaling:
func (e Employee) MarshalJSON() ([]byte, error) {
v := reflect.ValueOf(e)
result := make(map[string]interface{})
for i := 0; i < v.NumField(); i++ {
fieldName := v.Type().Field(i).Name
result[fieldName] = v.Field(i).Interface()
}
return json.Marshal(result)
}
It's handy but nests the embedded structs in the output::
{"JobRole":"Sales","Person":{"name":"Bob"}}
For a tiny struct like the one in the question, @Flimzy's answer is good but can be done more succinctly:
func (e Employee) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"jobRole": e.JobRole,
"name": e.Name,
})
}