encoding/json: fix panic for nil instances of TextMarshaler in map keys

This change adds a a check in the encodeWithString.resolve method
to ensure that a reflect.Value with kind Ptr is not nil before
the type assertion to TextMarshaler.

If the value is nil, the method returns a nil error, and the map key
encodes to an empty string.

Fixes #33675
This commit is contained in:
William Poussier 2019-08-17 21:41:48 +02:00
parent c485506b0a
commit 6c987c9084
2 changed files with 18 additions and 0 deletions

View File

@ -872,6 +872,9 @@ func (w *reflectWithString) resolve() error {
return nil return nil
} }
if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok { if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok {
if w.v.Kind() == reflect.Ptr && w.v.IsNil() {
return nil
}
buf, err := tm.MarshalText() buf, err := tm.MarshalText()
w.s = string(buf) w.s = string(buf)
return err return err

View File

@ -793,6 +793,21 @@ func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
} }
} }
// https://golang.org/issue/33675
func TestNilMarshalerTextMapKey(t *testing.T) {
b, err := Marshal(map[*unmarshalerText]int{
(*unmarshalerText)(nil): 1,
&unmarshalerText{"A", "B"}: 2,
})
if err != nil {
t.Fatalf("Failed to Marshal *text.Marshaler: %v", err)
}
const want = `{"":1,"A:B":2}`
if string(b) != want {
t.Errorf("Marshal map with *text.Marshaler keys: got %#q, want %#q", b, want)
}
}
var re = regexp.MustCompile var re = regexp.MustCompile
// syntactic checks on form of marshaled floating point numbers. // syntactic checks on form of marshaled floating point numbers.