Skip to content

Commit b68305f

Browse files
authored
Merge pull request #431 from orisano/fix/#426
fix: fixed handling of anonymous fields other than struct
2 parents 8a4a17d + 06ab2b4 commit b68305f

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

encode_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2629,3 +2629,18 @@ func TestCustomMarshalForMapKey(t *testing.T) {
26292629
assertErr(t, err)
26302630
assertEq(t, "custom map key", string(expected), string(got))
26312631
}
2632+
2633+
func TestIssue426(t *testing.T) {
2634+
type I interface {
2635+
Foo()
2636+
}
2637+
type A struct {
2638+
I
2639+
Val string
2640+
}
2641+
var s A
2642+
s.Val = "456"
2643+
2644+
b, _ := json.Marshal(s)
2645+
assertEq(t, "unexpected result", `{"I":null,"Val":"456"}`, string(b))
2646+
}

internal/encoder/compiler.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,13 @@ func (c *Compiler) structCode(typ *runtime.Type, isPtr bool) (*StructCode, error
617617
return code, nil
618618
}
619619

620+
func toElemType(t *runtime.Type) *runtime.Type {
621+
for t.Kind() == reflect.Ptr {
622+
t = t.Elem()
623+
}
624+
return t
625+
}
626+
620627
func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTag, isPtr, isOnlyOneFirstField bool) (*StructFieldCode, error) {
621628
field := tag.Field
622629
fieldType := runtime.Type2RType(field.Type)
@@ -626,7 +633,7 @@ func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTa
626633
key: tag.Key,
627634
tag: tag,
628635
offset: field.Offset,
629-
isAnonymous: field.Anonymous && !tag.IsTaggedKey,
636+
isAnonymous: field.Anonymous && !tag.IsTaggedKey && toElemType(fieldType).Kind() == reflect.Struct,
630637
isTaggedKey: tag.IsTaggedKey,
631638
isNilableType: c.isNilableType(fieldType),
632639
isNilCheck: true,

0 commit comments

Comments
 (0)