...

Source file src/encoding/json/example_marshaling_test.go

Documentation: encoding/json

		 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  }
		74  

View as plain text