github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/encoding/json/example_marshaling_test.go (about) 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. 4 5 package json_test 6 7 import ( 8 "github.com/shogo82148/std/encoding/json" 9 "github.com/shogo82148/std/fmt" 10 "github.com/shogo82148/std/log" 11 ) 12 13 const ( 14 Unknown Animal = iota 15 Gopher 16 Zebra 17 ) 18 19 func Example_customMarshalJSON() { 20 blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]` 21 var zoo []Animal 22 if err := json.Unmarshal([]byte(blob), &zoo); err != nil { 23 log.Fatal(err) 24 } 25 26 census := make(map[Animal]int) 27 for _, animal := range zoo { 28 census[animal] += 1 29 } 30 31 fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras: %d\n* Unknown: %d\n", 32 census[Gopher], census[Zebra], census[Unknown]) 33 34 // Output: 35 // Zoo Census: 36 // * Gophers: 3 37 // * Zebras: 2 38 // * Unknown: 3 39 }