diff options
| author | Ondřej Surý <ondrej@sury.org> | 2012-04-06 15:14:11 +0200 | 
|---|---|---|
| committer | Ondřej Surý <ondrej@sury.org> | 2012-04-06 15:14:11 +0200 | 
| commit | 505c19580e0f43fe5224431459cacb7c21edd93d (patch) | |
| tree | 79e2634c253d60afc0cc0b2f510dc7dcbb48497b /src/pkg/encoding/json/example_test.go | |
| parent | 1336a7c91e596c423a49d1194ea42d98bca0d958 (diff) | |
| download | golang-505c19580e0f43fe5224431459cacb7c21edd93d.tar.gz | |
Imported Upstream version 1upstream/1
Diffstat (limited to 'src/pkg/encoding/json/example_test.go')
| -rw-r--r-- | src/pkg/encoding/json/example_test.go | 83 | 
1 files changed, 83 insertions, 0 deletions
| diff --git a/src/pkg/encoding/json/example_test.go b/src/pkg/encoding/json/example_test.go new file mode 100644 index 000000000..b8d150eda --- /dev/null +++ b/src/pkg/encoding/json/example_test.go @@ -0,0 +1,83 @@ +// Copyright 2011 The Go Authors.  All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json_test + +import ( +	"encoding/json" +	"fmt" +	"io" +	"log" +	"os" +	"strings" +) + +func ExampleMarshal() { +	type ColorGroup struct { +		ID     int +		Name   string +		Colors []string +	} +	group := ColorGroup{ +		ID:     1, +		Name:   "Reds", +		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, +	} +	b, err := json.Marshal(group) +	if err != nil { +		fmt.Println("error:", err) +	} +	os.Stdout.Write(b) +	// Output: +	// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} +} + +func ExampleUnmarshal() { +	var jsonBlob = []byte(`[ +		{"Name": "Platypus", "Order": "Monotremata"}, +		{"Name": "Quoll",    "Order": "Dasyuromorphia"} +	]`) +	type Animal struct { +		Name  string +		Order string +	} +	var animals []Animal +	err := json.Unmarshal(jsonBlob, &animals) +	if err != nil { +		fmt.Println("error:", err) +	} +	fmt.Printf("%+v", animals) +	// Output: +	// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] +} + +// This example uses a Decoder to decode a stream of distinct JSON values. +func ExampleDecoder() { +	const jsonStream = ` +		{"Name": "Ed", "Text": "Knock knock."} +		{"Name": "Sam", "Text": "Who's there?"} +		{"Name": "Ed", "Text": "Go fmt."} +		{"Name": "Sam", "Text": "Go fmt who?"} +		{"Name": "Ed", "Text": "Go fmt yourself!"} +	` +	type Message struct { +		Name, Text string +	} +	dec := json.NewDecoder(strings.NewReader(jsonStream)) +	for { +		var m Message +		if err := dec.Decode(&m); err == io.EOF { +			break +		} else if err != nil { +			log.Fatal(err) +		} +		fmt.Printf("%s: %s\n", m.Name, m.Text) +	} +	// Output: +	// Ed: Knock knock. +	// Sam: Who's there? +	// Ed: Go fmt. +	// Sam: Go fmt who? +	// Ed: Go fmt yourself! +} | 
