github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/doc/progs/json1.go (about)

     1  // Copyright 2012 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 main
     6  
     7  import (
     8  	"encoding/json"
     9  	"log"
    10  	"reflect"
    11  )
    12  
    13  type Message struct {
    14  	Name string
    15  	Body string
    16  	Time int64
    17  }
    18  
    19  // STOP OMIT
    20  
    21  func Encode() {
    22  	m := Message{"Alice", "Hello", 1294706395881547000}
    23  	b, err := json.Marshal(m)
    24  
    25  	if err != nil {
    26  		panic(err)
    27  	}
    28  
    29  	expected := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)
    30  	if !reflect.DeepEqual(b, expected) {
    31  		log.Panicf("Error marshalling %q, expected %q, got %q.", m, expected, b)
    32  	}
    33  
    34  }
    35  
    36  func Decode() {
    37  	b := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)
    38  	var m Message
    39  	err := json.Unmarshal(b, &m)
    40  
    41  	if err != nil {
    42  		panic(err)
    43  	}
    44  
    45  	expected := Message{
    46  		Name: "Alice",
    47  		Body: "Hello",
    48  		Time: 1294706395881547000,
    49  	}
    50  
    51  	if !reflect.DeepEqual(m, expected) {
    52  		log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m)
    53  	}
    54  
    55  	m = Message{
    56  		Name: "Alice",
    57  		Body: "Hello",
    58  		Time: 1294706395881547000,
    59  	}
    60  
    61  	// STOP OMIT
    62  }
    63  
    64  func PartialDecode() {
    65  	b := []byte(`{"Name":"Bob","Food":"Pickle"}`)
    66  	var m Message
    67  	err := json.Unmarshal(b, &m)
    68  
    69  	// STOP OMIT
    70  
    71  	if err != nil {
    72  		panic(err)
    73  	}
    74  
    75  	expected := Message{
    76  		Name: "Bob",
    77  	}
    78  
    79  	if !reflect.DeepEqual(expected, m) {
    80  		log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m)
    81  	}
    82  }
    83  
    84  func main() {
    85  	Encode()
    86  	Decode()
    87  	PartialDecode()
    88  }