jsoniter_any_object_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package jsoniter
  2. import (
  3. "testing"
  4. "github.com/json-iterator/go/require"
  5. )
  6. func Test_read_object_as_any(t *testing.T) {
  7. should := require.New(t)
  8. any := Get([]byte(`{"a":"b","c":"d"}`))
  9. should.Equal(`{"a":"b","c":"d"}`, any.ToString())
  10. // partial parse
  11. should.Equal("b", any.Get("a").ToString())
  12. should.Equal("d", any.Get("c").ToString())
  13. should.Equal(2, len(any.Keys()))
  14. any = Get([]byte(`{"a":"b","c":"d"}`))
  15. // full parse
  16. should.Equal(2, len(any.Keys()))
  17. should.Equal(2, any.Size())
  18. should.True(any.ToBool())
  19. should.Equal(1, any.ToInt())
  20. should.Equal(Object, any.ValueType())
  21. should.Nil(any.LastError())
  22. should.Equal("b", any.GetObject()["a"].ToString())
  23. }
  24. func Test_object_lazy_any_get(t *testing.T) {
  25. should := require.New(t)
  26. any := Get([]byte(`{"a":{"b":{"c":"d"}}}`))
  27. should.Equal("d", any.Get("a", "b", "c").ToString())
  28. }
  29. func Test_object_lazy_any_get_all(t *testing.T) {
  30. should := require.New(t)
  31. any := Get([]byte(`{"a":[0],"b":[1]}`))
  32. should.Contains(any.Get('*', 0).ToString(), `"a":0`)
  33. }
  34. func Test_object_lazy_any_get_invalid(t *testing.T) {
  35. should := require.New(t)
  36. any := Get([]byte(`{}`))
  37. should.Equal(Invalid, any.Get("a", "b", "c").ValueType())
  38. should.Equal(Invalid, any.Get(1).ValueType())
  39. }
  40. func Test_wrap_object(t *testing.T) {
  41. should := require.New(t)
  42. type TestObject struct {
  43. Field1 string
  44. field2 string
  45. }
  46. any := Wrap(TestObject{"hello", "world"})
  47. should.Equal("hello", any.Get("Field1").ToString())
  48. any = Wrap(TestObject{"hello", "world"})
  49. should.Equal(2, any.Size())
  50. should.Equal(`{"Field1":"hello"}`, any.Get('*').ToString())
  51. }
  52. func Test_any_within_struct(t *testing.T) {
  53. should := require.New(t)
  54. type TestObject struct {
  55. Field1 Any
  56. Field2 Any
  57. }
  58. obj := TestObject{}
  59. err := UnmarshalFromString(`{"Field1": "hello", "Field2": [1,2,3]}`, &obj)
  60. should.Nil(err)
  61. should.Equal("hello", obj.Field1.ToString())
  62. should.Equal("[1,2,3]", obj.Field2.ToString())
  63. }