From 4235ca04c06fb1028aba2841aa587c1b3d598976 Mon Sep 17 00:00:00 2001 From: Nao Yonashiro Date: Thu, 24 Mar 2022 09:35:14 +0900 Subject: [PATCH] fix: an incompatible behavior on map key decoder fix #342 The map key decoder has an incompatible behavior when the type kind is string and the type has UnmarshalJSON. --- decode_test.go | 18 ++++++++++++++++++ internal/decoder/compile.go | 3 +++ 2 files changed, 21 insertions(+) diff --git a/decode_test.go b/decode_test.go index 3820173..57d9c6a 100644 --- a/decode_test.go +++ b/decode_test.go @@ -3889,3 +3889,21 @@ func TestIssue348(t *testing.T) { } } } + +type issue342 string + +func (t *issue342) UnmarshalJSON(b []byte) error { + panic("unreachable") +} + +func TestIssue342(t *testing.T) { + var v map[issue342]int + in := []byte(`{"a":1}`) + if err := json.Unmarshal(in, &v); err != nil { + t.Errorf("unexpected error: %v", err) + } + expected := 1 + if got := v["a"]; got != expected { + t.Errorf("unexpected result: got(%v) != expected(%v)", got, expected) + } +} diff --git a/internal/decoder/compile.go b/internal/decoder/compile.go index b2e9f57..bf17d1b 100644 --- a/internal/decoder/compile.go +++ b/internal/decoder/compile.go @@ -154,6 +154,9 @@ func compileMapKey(typ *runtime.Type, structName, fieldName string, structTypeTo if runtime.PtrTo(typ).Implements(unmarshalTextType) { return newUnmarshalTextDecoder(runtime.PtrTo(typ), structName, fieldName), nil } + if typ.Kind() == reflect.String { + return newStringDecoder(structName, fieldName), nil + } dec, err := compile(typ, structName, fieldName, structTypeToDecoder) if err != nil { return nil, err