git.lukeshu.com/go/lowmemjson@v0.3.9-0.20230723050957-72f6d13f6fb2/compat/json/borrowed_example_text_marshaling_test.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 // 5 // SPDX-License-Identifier: BSD-3-Clause 6 7 package json_test 8 9 import ( 10 "fmt" 11 "log" 12 "strings" 13 14 "git.lukeshu.com/go/lowmemjson/compat/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 // Output: 66 // Inventory Counts: 67 // * Small: 3 68 // * Large: 2 69 // * Unrecognized: 3 70 }