example_test.go 933 B

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