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 /doc/progs/json1.go | |
parent | 1336a7c91e596c423a49d1194ea42d98bca0d958 (diff) | |
download | golang-505c19580e0f43fe5224431459cacb7c21edd93d.tar.gz |
Imported Upstream version 1upstream/1
Diffstat (limited to 'doc/progs/json1.go')
-rw-r--r-- | doc/progs/json1.go | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/doc/progs/json1.go b/doc/progs/json1.go new file mode 100644 index 000000000..9e10f4743 --- /dev/null +++ b/doc/progs/json1.go @@ -0,0 +1,88 @@ +// Copyright 2012 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 main + +import ( + "encoding/json" + "log" + "reflect" +) + +type Message struct { + Name string + Body string + Time int64 +} + +// STOP OMIT + +func Encode() { + m := Message{"Alice", "Hello", 1294706395881547000} + b, err := json.Marshal(m) + + if err != nil { + panic(err) + } + + expected := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) + if !reflect.DeepEqual(b, expected) { + log.Panicf("Error marshalling %q, expected %q, got %q.", m, expected, b) + } + +} + +func Decode() { + b := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) + var m Message + err := json.Unmarshal(b, &m) + + if err != nil { + panic(err) + } + + expected := Message{ + Name: "Alice", + Body: "Hello", + Time: 1294706395881547000, + } + + if !reflect.DeepEqual(m, expected) { + log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m) + } + + m = Message{ + Name: "Alice", + Body: "Hello", + Time: 1294706395881547000, + } + + // STOP OMIT +} + +func PartialDecode() { + b := []byte(`{"Name":"Bob","Food":"Pickle"}`) + var m Message + err := json.Unmarshal(b, &m) + + // STOP OMIT + + if err != nil { + panic(err) + } + + expected := Message{ + Name: "Bob", + } + + if !reflect.DeepEqual(expected, m) { + log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m) + } +} + +func main() { + Encode() + Decode() + PartialDecode() +} |