github.com/zach-klippenstein/go@v0.0.0-20150108044943-fcfbeb3adf58/doc/progs/json1.go (about) 1 // run 2 3 // Copyright 2012 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 package main 8 9 import ( 10 "encoding/json" 11 "log" 12 "reflect" 13 ) 14 15 type Message struct { 16 Name string 17 Body string 18 Time int64 19 } 20 21 // STOP OMIT 22 23 func Encode() { 24 m := Message{"Alice", "Hello", 1294706395881547000} 25 b, err := json.Marshal(m) 26 27 if err != nil { 28 panic(err) 29 } 30 31 expected := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) 32 if !reflect.DeepEqual(b, expected) { 33 log.Panicf("Error marshalling %q, expected %q, got %q.", m, expected, b) 34 } 35 36 } 37 38 func Decode() { 39 b := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) 40 var m Message 41 err := json.Unmarshal(b, &m) 42 43 if err != nil { 44 panic(err) 45 } 46 47 expected := Message{ 48 Name: "Alice", 49 Body: "Hello", 50 Time: 1294706395881547000, 51 } 52 53 if !reflect.DeepEqual(m, expected) { 54 log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m) 55 } 56 57 m = Message{ 58 Name: "Alice", 59 Body: "Hello", 60 Time: 1294706395881547000, 61 } 62 63 // STOP OMIT 64 } 65 66 func PartialDecode() { 67 b := []byte(`{"Name":"Bob","Food":"Pickle"}`) 68 var m Message 69 err := json.Unmarshal(b, &m) 70 71 // STOP OMIT 72 73 if err != nil { 74 panic(err) 75 } 76 77 expected := Message{ 78 Name: "Bob", 79 } 80 81 if !reflect.DeepEqual(expected, m) { 82 log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m) 83 } 84 } 85 86 func main() { 87 Encode() 88 Decode() 89 PartialDecode() 90 }