Source file src/encoding/json/example_text_marshaling_test.go

Documentation: encoding/json

     1  // Copyright 2018 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 Size int
    15  
    16  const (
    17  	Unrecognized Size = iota
    18  	Small
    19  	Large
    20  )
    21  
    22  func (s *Size) UnmarshalText(text []byte) error {
    23  	switch strings.ToLower(string(text)) {
    24  	default:
    25  		*s = Unrecognized
    26  	case "small":
    27  		*s = Small
    28  	case "large":
    29  		*s = Large
    30  	}
    31  	return nil
    32  }
    33  
    34  func (s Size) MarshalText() ([]byte, error) {
    35  	var name string
    36  	switch s {
    37  	default:
    38  		name = "unrecognized"
    39  	case Small:
    40  		name = "small"
    41  	case Large:
    42  		name = "large"
    43  	}
    44  	return []byte(name), nil
    45  }
    46  
    47  func Example_textMarshalJSON() {
    48  	blob := `["small","regular","large","unrecognized","small","normal","small","large"]`
    49  	var inventory []Size
    50  	if err := json.Unmarshal([]byte(blob), &inventory); err != nil {
    51  		log.Fatal(err)
    52  	}
    53  
    54  	counts := make(map[Size]int)
    55  	for _, size := range inventory {
    56  		counts[size] += 1
    57  	}
    58  
    59  	fmt.Printf("Inventory Counts:\n* Small:        %d\n* Large:        %d\n* Unrecognized: %d\n",
    60  		counts[Small], counts[Large], counts[Unrecognized])
    61  
    62  	// Output:
    63  	// Inventory Counts:
    64  	// * Small:        3
    65  	// * Large:        2
    66  	// * Unrecognized: 3
    67  }
    68  

View as plain text