mirror of
https://github.com/golang/go.git
synced 2025-12-08 06:10:04 +00:00
49 lines
1 KiB
Go
49 lines
1 KiB
Go
|
|
// 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"
|
||
|
|
"os"
|
||
|
|
)
|
||
|
|
|
||
|
|
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
|
||
|
|
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)
|
||
|
|
}
|
||
|
|
|
||
|
|
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
|
||
|
|
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)
|
||
|
|
}
|