codekingpro/portable-devtools
114k
1// Copyright 2018 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4 5//go:build goexperiment.jsonv26 7package json_test8 9import (10 "fmt"11 "log"12 "strings"13 14 "encoding/json"15)16 17type Size int18 19const (20 Unrecognized Size = iota21 Small22 Large23)24 25func (s *Size) UnmarshalText(text []byte) error {26 switch strings.ToLower(string(text)) {27 default:28 *s = Unrecognized29 case "small":30 *s = Small31 case "large":32 *s = Large33 }34 return nil35}36 37func (s Size) MarshalText() ([]byte, error) {38 var name string39 switch s {40 default:41 name = "unrecognized"42 case Small:43 name = "small"44 case Large:45 name = "large"46 }47 return []byte(name), nil48}49 50func Example_textMarshalJSON() {51 blob := `["small","regular","large","unrecognized","small","normal","small","large"]`52 var inventory []Size53 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] += 160 }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: 368 // * Large: 269 // * Unrecognized: 370}71 