Merge pull request #431 from orisano/fix/#426

fix: fixed handling of anonymous fields other than struct
This commit is contained in:
Masaaki Goshima 2023-03-13 19:43:45 +09:00 committed by GitHub
commit b68305f5d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 1 deletions

View File

@ -2629,3 +2629,18 @@ func TestCustomMarshalForMapKey(t *testing.T) {
assertErr(t, err) assertErr(t, err)
assertEq(t, "custom map key", string(expected), string(got)) 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))
}

View File

@ -617,6 +617,13 @@ func (c *Compiler) structCode(typ *runtime.Type, isPtr bool) (*StructCode, error
return code, nil 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) { func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTag, isPtr, isOnlyOneFirstField bool) (*StructFieldCode, error) {
field := tag.Field field := tag.Field
fieldType := runtime.Type2RType(field.Type) fieldType := runtime.Type2RType(field.Type)
@ -626,7 +633,7 @@ func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTa
key: tag.Key, key: tag.Key,
tag: tag, tag: tag,
offset: field.Offset, offset: field.Offset,
isAnonymous: field.Anonymous && !tag.IsTaggedKey, isAnonymous: field.Anonymous && !tag.IsTaggedKey && toElemType(fieldType).Kind() == reflect.Struct,
isTaggedKey: tag.IsTaggedKey, isTaggedKey: tag.IsTaggedKey,
isNilableType: c.isNilableType(fieldType), isNilableType: c.isNilableType(fieldType),
isNilCheck: true, isNilCheck: true,