example_test.go 925 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package jsoniter_test
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/json-iterator/go"
  6. )
  7. func ExampleMarshal() {
  8. type ColorGroup struct {
  9. ID int
  10. Name string
  11. Colors []string
  12. }
  13. group := ColorGroup{
  14. ID: 1,
  15. Name: "Reds",
  16. Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
  17. }
  18. b, err := jsoniter.Marshal(group)
  19. if err != nil {
  20. fmt.Println("error:", err)
  21. }
  22. os.Stdout.Write(b)
  23. // Output:
  24. // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
  25. }
  26. func ExampleUnmarshal() {
  27. var jsonBlob = []byte(`[
  28. {"Name": "Platypus", "Order": "Monotremata"},
  29. {"Name": "Quoll", "Order": "Dasyuromorphia"}
  30. ]`)
  31. type Animal struct {
  32. Name string
  33. Order string
  34. }
  35. var animals []Animal
  36. err := jsoniter.Unmarshal(jsonBlob, &animals)
  37. if err != nil {
  38. fmt.Println("error:", err)
  39. }
  40. fmt.Printf("%+v", animals)
  41. // Output:
  42. // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
  43. }