Source file src/encoding/json/example_text_marshaling_test.go

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

View as plain text