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