Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix custom marshal for map's key #409

Merged
merged 2 commits into from Nov 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 26 additions & 2 deletions encode_test.go
Expand Up @@ -1022,19 +1022,28 @@ 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)
}
const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}`
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
Expand Down Expand Up @@ -2605,3 +2614,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))
}
2 changes: 0 additions & 2 deletions internal/encoder/compiler.go
Expand Up @@ -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):
goccy marked this conversation as resolved.
Show resolved Hide resolved
return c.marshalTextCode(typ)
}
Expand Down