example_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package jsoniter
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func ExampleMarshal() {
  7. type ColorGroup struct {
  8. ID int
  9. Name string
  10. Colors []string
  11. }
  12. group := ColorGroup{
  13. ID: 1,
  14. Name: "Reds",
  15. Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
  16. }
  17. b, err := Marshal(group)
  18. if err != nil {
  19. fmt.Println("error:", err)
  20. }
  21. os.Stdout.Write(b)
  22. // Output:
  23. // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
  24. }
  25. func ExampleUnmarshal() {
  26. var jsonBlob = []byte(`[
  27. {"Name": "Platypus", "Order": "Monotremata"},
  28. {"Name": "Quoll", "Order": "Dasyuromorphia"}
  29. ]`)
  30. type Animal struct {
  31. Name string
  32. Order string
  33. }
  34. var animals []Animal
  35. err := Unmarshal(jsonBlob, &animals)
  36. if err != nil {
  37. fmt.Println("error:", err)
  38. }
  39. fmt.Printf("%+v", animals)
  40. // Output:
  41. // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
  42. }
  43. func ExampleConfigFastest_Marshal() {
  44. type ColorGroup struct {
  45. ID int
  46. Name string
  47. Colors []string
  48. }
  49. group := ColorGroup{
  50. ID: 1,
  51. Name: "Reds",
  52. Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
  53. }
  54. stream := ConfigFastest.BorrowStream(nil)
  55. defer ConfigFastest.ReturnStream(stream)
  56. stream.WriteVal(group)
  57. if stream.Error != nil {
  58. fmt.Println("error:", stream.Error)
  59. }
  60. os.Stdout.Write(stream.Buffer())
  61. // Output:
  62. // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
  63. }
  64. func ExampleConfigFastest_Unmarshal() {
  65. var jsonBlob = []byte(`[
  66. {"Name": "Platypus", "Order": "Monotremata"},
  67. {"Name": "Quoll", "Order": "Dasyuromorphia"}
  68. ]`)
  69. type Animal struct {
  70. Name string
  71. Order string
  72. }
  73. var animals []Animal
  74. iter := ConfigFastest.BorrowIterator(jsonBlob)
  75. defer ConfigFastest.ReturnIterator(iter)
  76. iter.ReadVal(&animals)
  77. if iter.Error != nil {
  78. fmt.Println("error:", iter.Error)
  79. }
  80. fmt.Printf("%+v", animals)
  81. // Output:
  82. // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
  83. }
  84. func ExampleGet() {
  85. val := []byte(`{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}`)
  86. fmt.Printf(Get(val, "Colors", 0).ToString())
  87. // Output:
  88. // Crimson
  89. }