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