diff options
author | Luke Shumaker <lukeshu@datawire.io> | 2022-08-14 20:52:33 -0600 |
---|---|---|
committer | Luke Shumaker <lukeshu@datawire.io> | 2022-08-17 00:48:19 -0600 |
commit | 3ae8e37b8ca2b9a7769d659e134ee2711dc94b89 (patch) | |
tree | 35d23ddd779820dea1e239e96d5613c2d874a2b7 /compat/json/borrowed_example_marshaling_test.go | |
parent | 6b11bd03dd572a4c1b5bb2a72da5a556c7998c56 (diff) |
Borrow more test files [ci-skip]
Diffstat (limited to 'compat/json/borrowed_example_marshaling_test.go')
-rw-r--r-- | compat/json/borrowed_example_marshaling_test.go | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/compat/json/borrowed_example_marshaling_test.go b/compat/json/borrowed_example_marshaling_test.go new file mode 100644 index 0000000..7f15c74 --- /dev/null +++ b/compat/json/borrowed_example_marshaling_test.go @@ -0,0 +1,73 @@ +// Copyright 2016 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 ( + "encoding/json" + "fmt" + "log" + "strings" +) + +type Animal int + +const ( + Unknown Animal = iota + Gopher + Zebra +) + +func (a *Animal) UnmarshalJSON(b []byte) error { + var s string + if err := json.Unmarshal(b, &s); err != nil { + return err + } + switch strings.ToLower(s) { + default: + *a = Unknown + case "gopher": + *a = Gopher + case "zebra": + *a = Zebra + } + + return nil +} + +func (a Animal) MarshalJSON() ([]byte, error) { + var s string + switch a { + default: + s = "unknown" + case Gopher: + s = "gopher" + case Zebra: + s = "zebra" + } + + return json.Marshal(s) +} + +func Example_customMarshalJSON() { + blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]` + var zoo []Animal + if err := json.Unmarshal([]byte(blob), &zoo); err != nil { + log.Fatal(err) + } + + census := make(map[Animal]int) + for _, animal := range zoo { + census[animal] += 1 + } + + fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras: %d\n* Unknown: %d\n", + census[Gopher], census[Zebra], census[Unknown]) + + // Output: + // Zoo Census: + // * Gophers: 3 + // * Zebras: 2 + // * Unknown: 3 +} |