github.com/night-codes/go-json@v0.9.15/test/example/example_text_marshaling_test.go (about)

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