github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2015/json/unmarshaler0bad.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"encoding/json"
     7  	"fmt"
     8  	"log"
     9  	"strings"
    10  	"time"
    11  )
    12  
    13  const input = `
    14      {
    15          "name":"Gopher",
    16          "birthdate": "2009/11/10",
    17          "shirt-size": "XS"
    18      }
    19      `
    20  
    21  type Person struct {
    22  	Name string    `json:"name"`
    23  	Born time.Time `json:"birthdate"`
    24  	Size ShirtSize `json:"shirt-size"`
    25  }
    26  
    27  type ShirtSize byte
    28  
    29  const (
    30  	NA ShirtSize = iota
    31  	XS
    32  	S
    33  	M
    34  	L
    35  	XL
    36  )
    37  
    38  func (ss ShirtSize) String() string {
    39  	s, ok := map[ShirtSize]string{XS: "XS", S: "S", M: "M", L: "L", XL: "XL"}[ss]
    40  	if !ok {
    41  		return "invalid ShirtSize"
    42  	}
    43  	return s
    44  }
    45  
    46  func main() {
    47  	var p Person
    48  	dec := json.NewDecoder(strings.NewReader(input))
    49  	if err := dec.Decode(&p); err != nil {
    50  		log.Fatalf("parse person: %v", err)
    51  	}
    52  	fmt.Println(p)
    53  }