1package jsoniter 2 3import ( 4 "fmt" 5 "os" 6 "strings" 7) 8 9func ExampleMarshal() { 10 type ColorGroup struct { 11 ID int 12 Name string 13 Colors []string 14 } 15 group := ColorGroup{ 16 ID: 1, 17 Name: "Reds", 18 Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, 19 } 20 b, err := Marshal(group) 21 if err != nil { 22 fmt.Println("error:", err) 23 } 24 os.Stdout.Write(b) 25 // Output: 26 // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} 27} 28 29func ExampleUnmarshal() { 30 var jsonBlob = []byte(`[ 31 {"Name": "Platypus", "Order": "Monotremata"}, 32 {"Name": "Quoll", "Order": "Dasyuromorphia"} 33 ]`) 34 type Animal struct { 35 Name string 36 Order string 37 } 38 var animals []Animal 39 err := Unmarshal(jsonBlob, &animals) 40 if err != nil { 41 fmt.Println("error:", err) 42 } 43 fmt.Printf("%+v", animals) 44 // Output: 45 // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] 46} 47 48func ExampleConfigFastest_Marshal() { 49 type ColorGroup struct { 50 ID int 51 Name string 52 Colors []string 53 } 54 group := ColorGroup{ 55 ID: 1, 56 Name: "Reds", 57 Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, 58 } 59 stream := ConfigFastest.BorrowStream(nil) 60 defer ConfigFastest.ReturnStream(stream) 61 stream.WriteVal(group) 62 if stream.Error != nil { 63 fmt.Println("error:", stream.Error) 64 } 65 os.Stdout.Write(stream.Buffer()) 66 // Output: 67 // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} 68} 69 70func ExampleConfigFastest_Unmarshal() { 71 var jsonBlob = []byte(`[ 72 {"Name": "Platypus", "Order": "Monotremata"}, 73 {"Name": "Quoll", "Order": "Dasyuromorphia"} 74 ]`) 75 type Animal struct { 76 Name string 77 Order string 78 } 79 var animals []Animal 80 iter := ConfigFastest.BorrowIterator(jsonBlob) 81 defer ConfigFastest.ReturnIterator(iter) 82 iter.ReadVal(&animals) 83 if iter.Error != nil { 84 fmt.Println("error:", iter.Error) 85 } 86 fmt.Printf("%+v", animals) 87 // Output: 88 // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] 89} 90 91func ExampleGet() { 92 val := []byte(`{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}`) 93 fmt.Printf(Get(val, "Colors", 0).ToString()) 94 // Output: 95 // Crimson 96} 97 98func ExampleMyKey() { 99 hello := MyKey("hello") 100 output, _ := Marshal(map[*MyKey]string{&hello: "world"}) 101 fmt.Println(string(output)) 102 obj := map[*MyKey]string{} 103 Unmarshal(output, &obj) 104 for k, v := range obj { 105 fmt.Println(*k, v) 106 } 107 // Output: 108 // {"Hello":"world"} 109 // Hel world 110} 111 112type MyKey string 113 114func (m *MyKey) MarshalText() ([]byte, error) { 115 return []byte(strings.Replace(string(*m), "h", "H", -1)), nil 116} 117 118func (m *MyKey) UnmarshalText(text []byte) error { 119 *m = MyKey(text[:3]) 120 return nil 121} 122