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