Source file src/encoding/json/example_marshaling_test.go

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

View as plain text