Skip to content

Commit

Permalink
fix: fixed handling of anonymous fields other than struct
Browse files Browse the repository at this point in the history
fix #426
  • Loading branch information
orisano committed Feb 24, 2023
1 parent a2149a5 commit 06ab2b4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
15 changes: 15 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2629,3 +2629,18 @@ func TestCustomMarshalForMapKey(t *testing.T) {
assertErr(t, err)
assertEq(t, "custom map key", string(expected), string(got))
}

func TestIssue426(t *testing.T) {
type I interface {
Foo()
}
type A struct {
I
Val string
}
var s A
s.Val = "456"

b, _ := json.Marshal(s)
assertEq(t, "unexpected result", `{"I":null,"Val":"456"}`, string(b))
}
9 changes: 8 additions & 1 deletion internal/encoder/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,13 @@ func (c *Compiler) structCode(typ *runtime.Type, isPtr bool) (*StructCode, error
return code, nil
}

func toElemType(t *runtime.Type) *runtime.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}

func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTag, isPtr, isOnlyOneFirstField bool) (*StructFieldCode, error) {
field := tag.Field
fieldType := runtime.Type2RType(field.Type)
Expand All @@ -626,7 +633,7 @@ func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTa
key: tag.Key,
tag: tag,
offset: field.Offset,
isAnonymous: field.Anonymous && !tag.IsTaggedKey,
isAnonymous: field.Anonymous && !tag.IsTaggedKey && toElemType(fieldType).Kind() == reflect.Struct,
isTaggedKey: tag.IsTaggedKey,
isNilableType: c.isNilableType(fieldType),
isNilCheck: true,
Expand Down

0 comments on commit 06ab2b4

Please sign in to comment.