Skip to content

Commit a377e26

Browse files
committed
add map key example
1 parent 0ac74bb commit a377e26

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

example_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package jsoniter
33
import (
44
"fmt"
55
"os"
6+
"strings"
67
)
78

89
func ExampleMarshal() {
@@ -93,3 +94,30 @@ func ExampleGet() {
9394
// Output:
9495
// Crimson
9596
}
97+
98+
func ExampleMapKey() {
99+
hello := MyKey("hello")
100+
output, _ := Marshal(map[*MyKey]string{&hello: "world"})
101+
fmt.Println(string(output))
102+
obj := map[*MyKey]string{}
103+
Unmarshal(output, &obj)
104+
for k, v := range obj {
105+
fmt.Println(*k, v)
106+
}
107+
// Output:
108+
// {"Hello":"world"}
109+
// Hel world
110+
}
111+
112+
type MyKey string
113+
114+
115+
func (m *MyKey) MarshalText() ([]byte, error) {
116+
return []byte(strings.Replace(string(*m), "h", "H", -1)), nil
117+
}
118+
119+
func (m *MyKey) UnmarshalText(text []byte) error {
120+
*m = MyKey(text[:3])
121+
return nil
122+
}
123+

0 commit comments

Comments
 (0)