Fix custom map marshaling (#505)

* fix custom map parshaling

* add additional tests
This commit is contained in:
Владимир Атаманов 2024-05-09 13:53:38 +03:00 committed by GitHub
parent 581620b5c5
commit 3c67b038e0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 29 additions and 1 deletions

View File

@ -480,7 +480,7 @@ func (c *Compiler) mapCode(typ *runtime.Type) (*MapCode, error) {
func (c *Compiler) listElemCode(typ *runtime.Type) (Code, error) {
switch {
case c.isPtrMarshalJSONType(typ):
case c.implementsMarshalJSONType(typ) || c.implementsMarshalJSONType(runtime.PtrTo(typ)):
return c.marshalJSONCode(typ)
case !typ.Implements(marshalTextType) && runtime.PtrTo(typ).Implements(marshalTextType):
return c.marshalTextCode(typ)

View File

@ -16,6 +16,18 @@ func (coverSliceMarshalJSON) MarshalJSON() ([]byte, error) {
return []byte(`"hello"`), nil
}
type coverSliceMarshalJSONMap map[string]any
func (c coverSliceMarshalJSONMap) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any(c))
}
type coverSliceMarshalJSONMapPtr map[string]any
func (c *coverSliceMarshalJSONMapPtr) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any(*c))
}
type coverSliceMarshalText struct {
A int
}
@ -152,6 +164,22 @@ func TestCoverSlice(t *testing.T) {
name: "SliceMarshalJSON",
data: []coverSliceMarshalJSON{{A: 1}, {A: 2}},
},
{
name: "SliceMarshalJSONMap",
data: []coverSliceMarshalJSONMap{{"foo": "bar"}, {"some": 1}},
},
{
name: "SliceMarshalJSONMap",
data: []*coverSliceMarshalJSONMap{{"foo": "bar"}, {"some": 1}},
},
{
name: "SliceMarshalJSONMap",
data: []coverSliceMarshalJSONMapPtr{{"foo": "bar"}, {"some": 1}},
},
{
name: "SliceMarshalJSONMap",
data: []*coverSliceMarshalJSONMapPtr{{"foo": "bar"}, {"some": 1}},
},
{
name: "SliceMarshalText",
data: []coverSliceMarshalText{{A: 1}, {A: 2}},