| 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 |
//go:build goexperiment.jsonv2 |
| 6 |
|
| 7 |
package json_test |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"log" |
| 12 |
"strings" |
| 13 |
|
| 14 |
"encoding/json" |
| 15 |
) |
| 16 |
|
| 17 |
type Animal int |
| 18 |
|
| 19 |
const ( |
| 20 |
Unknown Animal = iota |
| 21 |
Gopher |
| 22 |
Zebra |
| 23 |
) |
| 24 |
|
| 25 |
func (a *Animal) UnmarshalJSON(b []byte) error { |
| 26 |
var s string |
| 27 |
if err := json.Unmarshal(b, &s); err != nil { |
| 28 |
return err |
| 29 |
} |
| 30 |
switch strings.ToLower(s) { |
| 31 |
default: |
| 32 |
*a = Unknown |
| 33 |
case "gopher": |
| 34 |
*a = Gopher |
| 35 |
case "zebra": |
| 36 |
*a = Zebra |
| 37 |
} |
| 38 |
|
| 39 |
return nil |
| 40 |
} |
| 41 |
|
| 42 |
func (a Animal) MarshalJSON() ([]byte, error) { |
| 43 |
var s string |
| 44 |
switch a { |
| 45 |
default: |
| 46 |
s = "unknown" |
| 47 |
case Gopher: |
| 48 |
s = "gopher" |
| 49 |
case Zebra: |
| 50 |
s = "zebra" |
| 51 |
} |
| 52 |
|
| 53 |
return json.Marshal(s) |
| 54 |
} |
| 55 |
|
| 56 |
func Example_customMarshalJSON() { |
| 57 |
blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]` |
| 58 |
var zoo []Animal |
| 59 |
if err := json.Unmarshal([]byte(blob), &zoo); err != nil { |
| 60 |
log.Fatal(err) |
| 61 |
} |
| 62 |
|
| 63 |
census := make(map[Animal]int) |
| 64 |
for _, animal := range zoo { |
| 65 |
census[animal] += 1 |
| 66 |
} |
| 67 |
|
| 68 |
fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras: %d\n* Unknown: %d\n", |
| 69 |
census[Gopher], census[Zebra], census[Unknown]) |
| 70 |
|
| 71 |
// Output: |
| 72 |
// Zoo Census: |
| 73 |
// * Gophers: 3 |
| 74 |
// * Zebras: 2 |
| 75 |
// * Unknown: 3 |
| 76 |
} |