libgo: update to Go 1.11
[official-gcc.git] / libgo / go / encoding / json / example_marshaling_test.go
blob1c4f783a693fb806a3ebfde38c2dc82e9d7e222d
1 // Copyright 2016 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.
5 // +build ignore
7 package json_test
9 import (
10 "encoding/json"
11 "fmt"
12 "log"
13 "strings"
16 type Animal int
18 const (
19 Unknown Animal = iota
20 Gopher
21 Zebra
24 func (a *Animal) UnmarshalJSON(b []byte) error {
25 var s string
26 if err := json.Unmarshal(b, &s); err != nil {
27 return err
29 switch strings.ToLower(s) {
30 default:
31 *a = Unknown
32 case "gopher":
33 *a = Gopher
34 case "zebra":
35 *a = Zebra
38 return nil
41 func (a Animal) MarshalJSON() ([]byte, error) {
42 var s string
43 switch a {
44 default:
45 s = "unknown"
46 case Gopher:
47 s = "gopher"
48 case Zebra:
49 s = "zebra"
52 return json.Marshal(s)
55 func Example_customMarshalJSON() {
56 blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]`
57 var zoo []Animal
58 if err := json.Unmarshal([]byte(blob), &zoo); err != nil {
59 log.Fatal(err)
62 census := make(map[Animal]int)
63 for _, animal := range zoo {
64 census[animal] += 1
67 fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras: %d\n* Unknown: %d\n",
68 census[Gopher], census[Zebra], census[Unknown])
70 // Output:
71 // Zoo Census:
72 // * Gophers: 3
73 // * Zebras: 2
74 // * Unknown: 3