Skip to content

Commit fb9af84

Browse files
cuonglmmvdan
authored andcommitted
encoding/json: support TextUnmarshaler for map keys with string underlying types
When unmarshaling to a map, the map's key type must either be a string, an integer, or implement encoding.TextUnmarshaler. But for a user defined type, reflect.Kind will not distinguish between the static type and the underlying type. In: var x MyString = "x" t := reflect.TypeOf(x) println(t.Kind() == reflect.String) the Kind of x is still reflect.String, even though the static type of x is MyString. Moreover, checking for the map's key type is a string occurs first, so even if the map key type MyString implements encoding.TextUnmarshaler, it will be ignored. To fix the bug, check for encoding.TextUnmarshaler first. Fixes #34437 Change-Id: I780e0b084575e1dddfbb433fe03857adf71d05fb Reviewed-on: https://go-review.googlesource.com/c/go/+/200237 Run-TryBot: Cuong Manh Le <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Daniel Martí <[email protected]>
1 parent 900ebcf commit fb9af84

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/encoding/json/decode.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -773,14 +773,14 @@ func (d *decodeState) object(v reflect.Value) error {
773773
kt := t.Key()
774774
var kv reflect.Value
775775
switch {
776-
case kt.Kind() == reflect.String:
777-
kv = reflect.ValueOf(key).Convert(kt)
778776
case reflect.PtrTo(kt).Implements(textUnmarshalerType):
779777
kv = reflect.New(kt)
780778
if err := d.literalStore(item, kv, true); err != nil {
781779
return err
782780
}
783781
kv = kv.Elem()
782+
case kt.Kind() == reflect.String:
783+
kv = reflect.ValueOf(key).Convert(kt)
784784
default:
785785
switch kt.Kind() {
786786
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:

src/encoding/json/decode_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -2411,3 +2411,23 @@ func TestUnmarshalRecursivePointer(t *testing.T) {
24112411
t.Fatal(err)
24122412
}
24132413
}
2414+
2415+
type textUnmarshalerString string
2416+
2417+
func (m *textUnmarshalerString) UnmarshalText(text []byte) error {
2418+
*m = textUnmarshalerString(strings.ToLower(string(text)))
2419+
return nil
2420+
}
2421+
2422+
// Test unmarshal to a map, with map key is a user defined type.
2423+
// See golang.org/issues/34437.
2424+
func TestUnmarshalMapWithTextUnmarshalerStringKey(t *testing.T) {
2425+
var p map[textUnmarshalerString]string
2426+
if err := Unmarshal([]byte(`{"FOO": "1"}`), &p); err != nil {
2427+
t.Fatalf("Unmarshal unexpected error: %v", err)
2428+
}
2429+
2430+
if _, ok := p["foo"]; !ok {
2431+
t.Errorf(`Key "foo" is not existed in map: %v`, p)
2432+
}
2433+
}

0 commit comments

Comments
 (0)