Merge pull request #409 from brongineers/master

Ignore MarshalJSON when encoding map's key
This commit is contained in:
Masaaki Goshima 2022-11-15 12:31:02 +09:00 committed by GitHub
commit 32ec93b983
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 4 deletions

View File

@ -1022,12 +1022,13 @@ func (u *unmarshalerText) UnmarshalText(b []byte) error {
} }
func TestTextMarshalerMapKeysAreSorted(t *testing.T) { func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
b, err := json.Marshal(map[unmarshalerText]int{ data := map[unmarshalerText]int{
{"x", "y"}: 1, {"x", "y"}: 1,
{"y", "x"}: 2, {"y", "x"}: 2,
{"a", "z"}: 3, {"a", "z"}: 3,
{"z", "a"}: 4, {"z", "a"}: 4,
}) }
b, err := json.Marshal(data)
if err != nil { if err != nil {
t.Fatalf("Failed to Marshal text.Marshaler: %v", err) t.Fatalf("Failed to Marshal text.Marshaler: %v", err)
} }
@ -1035,6 +1036,14 @@ func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
if string(b) != want { if string(b) != want {
t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", 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 // https://golang.org/issue/33675
@ -2605,3 +2614,18 @@ func TestIssue386(t *testing.T) {
t.Error(err) 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))
}

View File

@ -506,8 +506,6 @@ func (c *Compiler) listElemCode(typ *runtime.Type) (Code, error) {
func (c *Compiler) mapKeyCode(typ *runtime.Type) (Code, error) { func (c *Compiler) mapKeyCode(typ *runtime.Type) (Code, error) {
switch { switch {
case c.implementsMarshalJSON(typ):
return c.marshalJSONCode(typ)
case c.implementsMarshalText(typ): case c.implementsMarshalText(typ):
return c.marshalTextCode(typ) return c.marshalTextCode(typ)
} }