The documentation states:
Anonymous struct fields are usually marshaled as if their inner exported fields were fields in the outer struct.
For examble:
type foo struct {
Foo1 string `json:"foo1"`
Foo2 string `json:"foo2"`
}
type boo struct {
Boo1 string `json:"boo1"`
foo
}
and I do this:
s := boo{
Boo: "boo1",
foo: foo{
Foo1: "foo1",
Foo2: "foo2",
},
}
b, err := json.MarshalIndent(s, "", " ")
fmt.Println(string(b))
I get this:
{
"boo1": "boo1",
"foo1": "foo1",
"foo2": "foo2"
}
But how can I achieve the same result when the foo is Not an anonymous struct? Meaning:
type boo struct {
Boo string `json:"boo"`
Foo foo
}
And also unmarshaling the json.
You have to implement a custom
json.Marshaler
for that.https://play.golang.org/p/Go1w9quPkMa
A note on "anonymous"
The label anonymous as you're using it, and as it is used in the documentation you quoted, is outdated and imprecise. The proper label for a field without an explicit name is embedded.
https://golang.org/ref/spec#Struct_types
The distinction is important because there is such a thing as "anonymous struct fields" in Go, it's used quite often but it is different from embedded fields. For example: