Skip to content

Commit 2b59b15

Browse files
odeke-emadg
authored andcommitted
encoding/json: example on MarshalJSON, UnmarshalJSON
Updates #16360. Change-Id: I5bf13d3367e68c5d8435f6ef2161d5a74cc747a7 Reviewed-on: https://go-review.googlesource.com/29611 Reviewed-by: Andrew Gerrand <[email protected]> Run-TryBot: Andrew Gerrand <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent 43f954e commit 2b59b15

File tree

1 file changed

+73
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)