From 705f51716bfc706f41209b07164a3882b6be2b96 Mon Sep 17 00:00:00 2001 From: brongineers Date: Sun, 13 Nov 2022 21:05:50 +0300 Subject: [PATCH 1/2] fix custom marshal for map key --- encode_test.go | 15 +++++++++++++++ internal/encoder/compiler.go | 2 -- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/encode_test.go b/encode_test.go index b2cbceb7..c7afadb7 100644 --- a/encode_test.go +++ b/encode_test.go @@ -2605,3 +2605,18 @@ func TestIssue386(t *testing.T) { t.Error(err) } } + +type customMapKey string + +func (b customMapKey) MarshalJSON() ([]byte, error) { + return []byte("[]"), nil +} + +func TestCustomMarshalForMapKey(t *testing.T) { + m := map[customMapKey]string{customMapKey("skipcustom"): "test"} + expected, err := stdjson.Marshal(m) + assertErr(t, err) + got, err := json.Marshal(m) + assertErr(t, err) + assertEq(t, "custom map key", string(expected), string(got)) +} diff --git a/internal/encoder/compiler.go b/internal/encoder/compiler.go index bf5e0f94..3b3ff3fd 100644 --- a/internal/encoder/compiler.go +++ b/internal/encoder/compiler.go @@ -506,8 +506,6 @@ func (c *Compiler) listElemCode(typ *runtime.Type) (Code, error) { func (c *Compiler) mapKeyCode(typ *runtime.Type) (Code, error) { switch { - case c.implementsMarshalJSON(typ): - return c.marshalJSONCode(typ) case c.implementsMarshalText(typ): return c.marshalTextCode(typ) } From 6bca98964369e64b3157ae166c54af60834ef1eb Mon Sep 17 00:00:00 2001 From: brongineers Date: Mon, 14 Nov 2022 22:11:00 +0300 Subject: [PATCH 2/2] test key map MarshalText with std --- encode_test.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/encode_test.go b/encode_test.go index c7afadb7..63740f35 100644 --- a/encode_test.go +++ b/encode_test.go @@ -1022,12 +1022,13 @@ func (u *unmarshalerText) UnmarshalText(b []byte) error { } func TestTextMarshalerMapKeysAreSorted(t *testing.T) { - b, err := json.Marshal(map[unmarshalerText]int{ + data := map[unmarshalerText]int{ {"x", "y"}: 1, {"y", "x"}: 2, {"a", "z"}: 3, {"z", "a"}: 4, - }) + } + b, err := json.Marshal(data) if err != nil { t.Fatalf("Failed to Marshal text.Marshaler: %v", err) } @@ -1035,6 +1036,14 @@ func TestTextMarshalerMapKeysAreSorted(t *testing.T) { if string(b) != want { t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", b, want) } + + b, err = stdjson.Marshal(data) + if err != nil { + t.Fatalf("Failed to std Marshal text.Marshaler: %v", err) + } + if string(b) != want { + t.Errorf("std Marshal map with text.Marshaler keys: got %#q, want %#q", b, want) + } } // https://golang.org/issue/33675