jsoniter_demo_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package jsoniter
  2. import (
  3. "fmt"
  4. "testing"
  5. "github.com/json-iterator/go/require"
  6. "unsafe"
  7. "strconv"
  8. )
  9. func Test_bind_api_demo(t *testing.T) {
  10. should := require.New(t)
  11. val := []int{}
  12. err := UnmarshalFromString(`[0,1,2,3] `, &val)
  13. should.Nil(err)
  14. should.Equal([]int{0, 1, 2, 3}, val)
  15. }
  16. func Test_iterator_api_demo(t *testing.T) {
  17. iter := ParseString(`[0,1,2,3]`)
  18. total := 0
  19. for iter.ReadArray() {
  20. total += iter.ReadInt()
  21. }
  22. fmt.Println(total)
  23. }
  24. type DocumentMatch struct {
  25. Index string `json:"index,omitempty"`
  26. ID string `json:"id"`
  27. Score float64 `json:"score"`
  28. Sort []string `json:"sort,omitempty"`
  29. }
  30. type DocumentMatchCollection []*DocumentMatch
  31. type SearchResult struct {
  32. Hits DocumentMatchCollection `json:"hits"`
  33. }
  34. func Test2(t *testing.T) {
  35. RegisterTypeEncoder("float64", func(ptr unsafe.Pointer, stream *Stream) {
  36. t := *((*float64)(ptr))
  37. stream.WriteRaw(strconv.FormatFloat(t, 'E', -1, 64))
  38. })
  39. hits := []byte(`{"hits":[{"index":"geo","id":"firehouse_grill_brewery","score":3.584608106366055e-07,
  40. "sort":[" \u0001@\t\u0007\u0013;a\u001b}W"]},
  41. {"index":"geo","id":"jack_s_brewing","score":2.3332790568885077e-07,
  42. "sort":[" \u0001@\u0013{w?.\"0\u0010"]},
  43. {"index":"geo","id":"brewpub_on_the_green","score":2.3332790568885077e-07,
  44. "sort":[" \u0001@\u0014\u0017+\u00137QZG"]}]}`)
  45. var h SearchResult
  46. err := Unmarshal(hits, &h)
  47. fmt.Printf("SR %+v \n", h.Hits[0])
  48. b, err := Marshal(h.Hits[0])
  49. if err != nil {
  50. fmt.Printf("error marshalling search res: %v", err)
  51. //return
  52. }
  53. fmt.Printf("SR %s \n", string(b))
  54. }