Skip to content

Commit

Permalink
Fix custom map marshaling (#505)
Browse files Browse the repository at this point in the history
* fix custom map parshaling

* add additional tests
  • Loading branch information
viewsharp authored May 9, 2024
1 parent 581620b commit 3c67b03
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/encoder/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
28 changes: 28 additions & 0 deletions test/cover/cover_slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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}},
Expand Down

0 comments on commit 3c67b03

Please sign in to comment.