Fix encoding of anonymous struct

This commit is contained in:
Masaaki Goshima 2021-02-09 09:20:48 +09:00
parent b286747e6b
commit 0d57bf1014
2 changed files with 84 additions and 1 deletions

View File

@ -1116,7 +1116,7 @@ func encodeAnonymousStructFieldPairMap(tags structTags, named string, valueCode
isTaggedKey: f.isTaggedKey,
})
if f.next != nil && f.nextField != f.next && f.next.op.codeType() == codeStructField {
for k, v := range encodeAnonymousStructFieldPairMap(tags, named, f.next) {
for k, v := range encodeAnonymousFieldPairRecursively(tags, named, f.next) {
anonymousFields[k] = append(anonymousFields[k], v...)
}
}
@ -1129,6 +1129,42 @@ func encodeAnonymousStructFieldPairMap(tags structTags, named string, valueCode
return anonymousFields
}
func encodeAnonymousFieldPairRecursively(tags structTags, named string, valueCode *opcode) map[string][]structFieldPair {
anonymousFields := map[string][]structFieldPair{}
f := valueCode
var prevAnonymousField *opcode
for {
if f.displayKey == "" {
if f.nextField == nil {
break
}
prevAnonymousField = f
f = f.nextField
continue
}
if strings.Contains(f.op.String(), "Anonymous") {
key := fmt.Sprintf("%s.%s", named, f.displayKey)
anonymousFields[key] = append(anonymousFields[key], structFieldPair{
prevField: prevAnonymousField,
curField: f,
isTaggedKey: f.isTaggedKey,
})
if f.next != nil && f.nextField != f.next && f.next.op.codeType() == codeStructField {
for k, v := range encodeAnonymousFieldPairRecursively(tags, named, f.next) {
anonymousFields[k] = append(anonymousFields[k], v...)
}
}
}
if f.nextField == nil {
break
}
prevAnonymousField = f
f = f.nextField
}
return anonymousFields
}
func encodeOptimizeConflictAnonymousFields(anonymousFields map[string][]structFieldPair) {
removedFields := map[*opcode]struct{}{}
for _, fieldPairs := range anonymousFields {

View File

@ -409,6 +409,53 @@ func Test_Marshal(t *testing.T) {
})
}
func TestIssue116(t *testing.T) {
t.Run("first", func(t *testing.T) {
type Boo struct{ B string }
type Struct struct {
A int
Boo *Boo
}
type Embedded struct {
Struct
}
b, err := json.Marshal(Embedded{Struct: Struct{
A: 1,
Boo: &Boo{B: "foo"},
}})
if err != nil {
t.Fatal(err)
}
expected := `{"A":1,"Boo":{"B":"foo"}}`
actual := string(b)
if actual != expected {
t.Fatalf("expected %s but got %s", expected, actual)
}
})
t.Run("second", func(t *testing.T) {
type Boo struct{ B string }
type Struct struct {
A int
B *Boo
}
type Embedded struct {
Struct
}
b, err := json.Marshal(Embedded{Struct: Struct{
A: 1,
B: &Boo{B: "foo"},
}})
if err != nil {
t.Fatal(err)
}
actual := string(b)
expected := `{"A":1,"B":{"B":"foo"}}`
if actual != expected {
t.Fatalf("expected %s but got %s", expected, actual)
}
})
}
type marshalJSON struct{}
func (*marshalJSON) MarshalJSON() ([]byte, error) {