2020-08-27 15:02:44 +03:00
|
|
|
// Copyright 2018 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package json_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/goccy/go-json"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Size int
|
|
|
|
|
|
|
|
const (
|
2020-09-17 15:50:27 +03:00
|
|
|
unrecognized Size = iota
|
|
|
|
small
|
|
|
|
large
|
2020-08-27 15:02:44 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Size) UnmarshalText(text []byte) error {
|
|
|
|
switch strings.ToLower(string(text)) {
|
|
|
|
default:
|
2020-09-17 15:50:27 +03:00
|
|
|
*s = unrecognized
|
2020-08-27 15:02:44 +03:00
|
|
|
case "small":
|
2020-09-17 15:50:27 +03:00
|
|
|
*s = small
|
2020-08-27 15:02:44 +03:00
|
|
|
case "large":
|
2020-09-17 15:50:27 +03:00
|
|
|
*s = large
|
2020-08-27 15:02:44 +03:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s Size) MarshalText() ([]byte, error) {
|
|
|
|
var name string
|
|
|
|
switch s {
|
|
|
|
default:
|
|
|
|
name = "unrecognized"
|
2020-09-17 15:50:27 +03:00
|
|
|
case small:
|
2020-08-27 15:02:44 +03:00
|
|
|
name = "small"
|
2020-09-17 15:50:27 +03:00
|
|
|
case large:
|
2020-08-27 15:02:44 +03:00
|
|
|
name = "large"
|
|
|
|
}
|
|
|
|
return []byte(name), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func Example_textMarshalJSON() {
|
|
|
|
blob := `["small","regular","large","unrecognized","small","normal","small","large"]`
|
|
|
|
var inventory []Size
|
|
|
|
if err := json.Unmarshal([]byte(blob), &inventory); err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
counts := make(map[Size]int)
|
|
|
|
for _, size := range inventory {
|
|
|
|
counts[size] += 1
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Printf("Inventory Counts:\n* Small: %d\n* Large: %d\n* Unrecognized: %d\n",
|
2020-09-17 15:50:27 +03:00
|
|
|
counts[small], counts[large], counts[unrecognized])
|
2020-08-27 15:02:44 +03:00
|
|
|
|
|
|
|
// Output:
|
|
|
|
// Inventory Counts:
|
|
|
|
// * Small: 3
|
|
|
|
// * Large: 2
|
|
|
|
// * Unrecognized: 3
|
|
|
|
}
|