jsoniter_reflect_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package jsoniter
  2. import (
  3. "testing"
  4. "fmt"
  5. "encoding/json"
  6. )
  7. func Test_reflect_str(t *testing.T) {
  8. iter := ParseString(`"hello"`)
  9. str := ""
  10. iter.Read(&str)
  11. if str != "hello" {
  12. t.Fatal(str)
  13. }
  14. }
  15. type StructOfString struct {
  16. field1 string
  17. field2 string
  18. }
  19. func Test_reflect_struct_string(t *testing.T) {
  20. iter := ParseString(`{"field1": "hello", "field2": "world"}`)
  21. struct_ := StructOfString{}
  22. iter.Read(&struct_)
  23. if struct_.field1 != "hello" {
  24. fmt.Println(iter.Error)
  25. t.Fatal(struct_.field1)
  26. }
  27. if struct_.field2 != "world" {
  28. fmt.Println(iter.Error)
  29. t.Fatal(struct_.field1)
  30. }
  31. }
  32. type StructOfStringPtr struct {
  33. field1 *string
  34. field2 *string
  35. }
  36. func Test_reflect_struct_string_ptr(t *testing.T) {
  37. iter := ParseString(`{"field1": null, "field2": "world"}`)
  38. struct_ := StructOfStringPtr{}
  39. iter.Read(&struct_)
  40. if struct_.field1 != nil {
  41. fmt.Println(iter.Error)
  42. t.Fatal(struct_.field1)
  43. }
  44. if *struct_.field2 != "world" {
  45. fmt.Println(iter.Error)
  46. t.Fatal(struct_.field1)
  47. }
  48. }
  49. func Test_reflect_array(t *testing.T) {
  50. iter := ParseString(`{"hello", "world"}`)
  51. array := []string{}
  52. iter.Read(&array)
  53. if len(array) != 2 {
  54. fmt.Println(iter.Error)
  55. t.Fatal(len(array))
  56. }
  57. if array[0] != "hello" {
  58. fmt.Println(iter.Error)
  59. t.Fatal(array[0])
  60. }
  61. if array[1] != "world" {
  62. fmt.Println(iter.Error)
  63. t.Fatal(array[1])
  64. }
  65. }
  66. func Benchmark_jsoniter_reflect(b *testing.B) {
  67. b.ReportAllocs()
  68. for n := 0; n < b.N; n++ {
  69. iter := ParseString(`{"field1": "hello", "field2": "world"}`)
  70. struct_ := StructOfString{}
  71. iter.Read(&struct_)
  72. }
  73. }
  74. func Benchmark_jsoniter_direct(b *testing.B) {
  75. b.ReportAllocs()
  76. for n := 0; n < b.N; n++ {
  77. iter := ParseString(`{"field1": "hello", "field2": "world"}`)
  78. struct_ := StructOfString{}
  79. for field := iter.ReadObject(); field != ""; field = iter.ReadObject() {
  80. switch field {
  81. case "field1":
  82. struct_.field1 = iter.ReadString()
  83. case "field2":
  84. struct_.field2 = iter.ReadString()
  85. default:
  86. iter.Skip()
  87. }
  88. }
  89. }
  90. }
  91. func Benchmark_json_reflect(b *testing.B) {
  92. b.ReportAllocs()
  93. for n := 0; n < b.N; n++ {
  94. struct_ := StructOfString{}
  95. json.Unmarshal([]byte(`{"field1": "hello", "field2": "world"}`), &struct_)
  96. }
  97. }