From 3c67b038e0dcaa3b8ea3a55b5fe2a4fb6abde75f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=BB=D0=B0=D0=B4=D0=B8=D0=BC=D0=B8=D1=80=20=D0=90?= =?UTF-8?q?=D1=82=D0=B0=D0=BC=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Thu, 9 May 2024 13:53:38 +0300 Subject: [PATCH] Fix custom map marshaling (#505) * fix custom map parshaling * add additional tests --- internal/encoder/compiler.go | 2 +- test/cover/cover_slice_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/internal/encoder/compiler.go b/internal/encoder/compiler.go index 3ae39ba..37b7aa3 100644 --- a/internal/encoder/compiler.go +++ b/internal/encoder/compiler.go @@ -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) diff --git a/test/cover/cover_slice_test.go b/test/cover/cover_slice_test.go index 61de9a5..70a0306 100644 --- a/test/cover/cover_slice_test.go +++ b/test/cover/cover_slice_test.go @@ -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}},