1
0
mirror of https://github.com/json-iterator/go.git synced 2024-12-03 08:45:22 +02:00
json-iterator/example_test.go

98 lines
2.2 KiB
Go
Raw Normal View History

2017-06-05 14:37:08 +02:00
package jsoniter_test
import (
"fmt"
"os"
2017-06-09 10:28:20 +02:00
"github.com/json-iterator/go"
2017-06-05 14:37:08 +02:00
)
2017-06-05 16:10:01 +02:00
func ExampleMarshal() {
2017-06-05 14:37:08 +02:00
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := jsoniter.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
// Output:
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
}
2017-06-08 06:07:03 +02:00
2017-06-08 06:08:47 +02:00
func ExampleUnmarshal() {
2017-06-08 06:07:03 +02:00
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
2017-06-09 10:25:58 +02:00
Name string
Order string
2017-06-08 06:07:03 +02:00
}
var animals []Animal
2017-06-09 10:25:58 +02:00
err := jsoniter.Unmarshal(jsonBlob, &animals)
2017-06-08 06:07:03 +02:00
if err != nil {
2017-06-09 10:25:58 +02:00
fmt.Println("error:", err)
2017-06-08 06:07:03 +02:00
}
fmt.Printf("%+v", animals)
// Output:
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
2017-06-09 10:25:58 +02:00
}
2017-06-17 11:14:34 +02:00
func ExampleMarshalWithBestPerformance() {
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
stream := jsoniter.ConfigFastest.BorrowStream(nil)
defer jsoniter.ConfigFastest.ReturnStream(stream)
stream.WriteVal(group)
if stream.Error != nil {
fmt.Println("error:", stream.Error)
}
os.Stdout.Write(stream.Buffer())
// Output:
// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
}
func ExampleUnmarshalWithBestPerformance() {
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
iter := jsoniter.ConfigFastest.BorrowIterator(jsonBlob)
defer jsoniter.ConfigFastest.ReturnIterator(iter)
iter.ReadVal(&animals)
if iter.Error != nil {
fmt.Println("error:", iter.Error)
}
fmt.Printf("%+v", animals)
// Output:
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
2017-06-17 15:11:23 +02:00
}
2017-06-18 17:42:23 +02:00
func ExampleOneLine() {
val := []byte(`{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}`)
fmt.Printf(jsoniter.Get(val, "Colors", 0).ToString())
// Output:
// Crimson
2017-06-19 17:43:53 +02:00
}