...
1
2
3
4
5 package json_test
6
7 import (
8 "fmt"
9 "log"
10 "strings"
11
12 "github.com/goccy/go-json"
13 )
14
15 type Size int
16
17 const (
18 unrecognized Size = iota
19 small
20 large
21 )
22
23 func (s *Size) UnmarshalText(text []byte) error {
24 switch strings.ToLower(string(text)) {
25 default:
26 *s = unrecognized
27 case "small":
28 *s = small
29 case "large":
30 *s = large
31 }
32 return nil
33 }
34
35 func (s Size) MarshalText() ([]byte, error) {
36 var name string
37 switch s {
38 default:
39 name = "unrecognized"
40 case small:
41 name = "small"
42 case large:
43 name = "large"
44 }
45 return []byte(name), nil
46 }
47
48 func Example_textMarshalJSON() {
49 blob := `["small","regular","large","unrecognized","small","normal","small","large"]`
50 var inventory []Size
51 if err := json.Unmarshal([]byte(blob), &inventory); err != nil {
52 log.Fatal(err)
53 }
54
55 counts := make(map[Size]int)
56 for _, size := range inventory {
57 counts[size] += 1
58 }
59
60 fmt.Printf("Inventory Counts:\n* Small: %d\n* Large: %d\n* Unrecognized: %d\n",
61 counts[small], counts[large], counts[unrecognized])
62
63
64
65
66
67
68 }
69
View as plain text