jsoniter_nested_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package jsoniter
  2. import (
  3. "encoding/json"
  4. "reflect"
  5. "testing"
  6. )
  7. type Level1 struct {
  8. Hello []Level2
  9. }
  10. type Level2 struct {
  11. World string
  12. }
  13. func Test_nested(t *testing.T) {
  14. iter := ParseString(`{"hello": [{"world": "value1"}, {"world": "value2"}]}`)
  15. l1 := Level1{}
  16. for l1Field := iter.ReadObject(); l1Field != ""; l1Field = iter.ReadObject() {
  17. switch l1Field {
  18. case "hello":
  19. l2Array := []Level2{}
  20. for iter.ReadArray() {
  21. l2 := Level2{}
  22. for l2Field := iter.ReadObject(); l2Field != ""; l2Field = iter.ReadObject() {
  23. switch l2Field {
  24. case "world":
  25. l2.World = iter.ReadString()
  26. default:
  27. iter.reportError("bind l2", "unexpected field: "+l2Field)
  28. }
  29. }
  30. l2Array = append(l2Array, l2)
  31. }
  32. l1.Hello = l2Array
  33. default:
  34. iter.reportError("bind l1", "unexpected field: "+l1Field)
  35. }
  36. }
  37. if !reflect.DeepEqual(l1, Level1{
  38. Hello: []Level2{
  39. {World: "value1"},
  40. {World: "value2"},
  41. },
  42. }) {
  43. t.Fatal(l1)
  44. }
  45. }
  46. func Benchmark_jsoniter_nested(b *testing.B) {
  47. for n := 0; n < b.N; n++ {
  48. iter := ParseString(`{"hello": [{"world": "value1"}, {"world": "value2"}]}`)
  49. l1 := Level1{}
  50. for l1Field := iter.ReadObject(); l1Field != ""; l1Field = iter.ReadObject() {
  51. switch l1Field {
  52. case "hello":
  53. l1.Hello = readLevel1Hello(iter)
  54. default:
  55. iter.Skip()
  56. }
  57. }
  58. }
  59. }
  60. func readLevel1Hello(iter *Iterator) []Level2 {
  61. l2Array := make([]Level2, 0, 2)
  62. for iter.ReadArray() {
  63. l2 := Level2{}
  64. for l2Field := iter.ReadObject(); l2Field != ""; l2Field = iter.ReadObject() {
  65. switch l2Field {
  66. case "world":
  67. l2.World = iter.ReadString()
  68. default:
  69. iter.Skip()
  70. }
  71. }
  72. l2Array = append(l2Array, l2)
  73. }
  74. return l2Array
  75. }
  76. func Benchmark_json_nested(b *testing.B) {
  77. for n := 0; n < b.N; n++ {
  78. l1 := Level1{}
  79. json.Unmarshal([]byte(`{"hello": [{"world": "value1"}, {"world": "value2"}]}`), &l1)
  80. }
  81. }