github.com/yukk001/go1.10.8@v0.0.0-20190813125351-6df2d3982e20/doc/progs/json4.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 FamilyMember struct { 14 Name string 15 Age int 16 Parents []string 17 } 18 19 // STOP OMIT 20 21 func Decode() { 22 b := []byte(`{"Name":"Bob","Age":20,"Parents":["Morticia", "Gomez"]}`) 23 var m FamilyMember 24 err := json.Unmarshal(b, &m) 25 26 // STOP OMIT 27 28 if err != nil { 29 panic(err) 30 } 31 32 expected := FamilyMember{ 33 Name: "Bob", 34 Age: 20, 35 Parents: []string{"Morticia", "Gomez"}, 36 } 37 38 if !reflect.DeepEqual(expected, m) { 39 log.Panicf("Error unmarshaling %q, expected %q, got %q", b, expected, m) 40 } 41 } 42 43 func main() { 44 Decode() 45 }