jsoniter_interface_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package jsoniter
  2. import (
  3. "testing"
  4. "github.com/json-iterator/go/require"
  5. "unsafe"
  6. )
  7. func Test_write_array_of_interface(t *testing.T) {
  8. should := require.New(t)
  9. array := []interface{}{"hello"}
  10. str, err := MarshalToString(array)
  11. should.Nil(err)
  12. should.Equal(`["hello"]`, str)
  13. }
  14. func Test_write_map_of_interface(t *testing.T) {
  15. should := require.New(t)
  16. val := map[string]interface{}{"hello":"world"}
  17. str, err := MarshalToString(val)
  18. should.Nil(err)
  19. should.Equal(`{"hello":"world"}`, str)
  20. }
  21. func Test_write_map_of_interface_in_struct(t *testing.T) {
  22. type TestObject struct {
  23. Field map[string]interface{}
  24. }
  25. should := require.New(t)
  26. val := TestObject{map[string]interface{}{"hello":"world"}}
  27. str, err := MarshalToString(val)
  28. should.Nil(err)
  29. should.Equal(`{"Field":{"hello":"world"}}`, str)
  30. }
  31. func Test_write_map_of_interface_in_struct_with_two_fields(t *testing.T) {
  32. type TestObject struct {
  33. Field map[string]interface{}
  34. Field2 string
  35. }
  36. should := require.New(t)
  37. val := TestObject{map[string]interface{}{"hello":"world"}, ""}
  38. str, err := MarshalToString(val)
  39. should.Nil(err)
  40. should.Equal(`{"Field":{"hello":"world"},"Field2":""}`, str)
  41. }
  42. type MyInterface interface {
  43. Hello() string
  44. }
  45. type MyString string
  46. func (ms MyString) Hello() string {
  47. return string(ms)
  48. }
  49. func Test_write_map_of_custom_interface(t *testing.T) {
  50. should := require.New(t)
  51. myStr := MyString("world")
  52. should.Equal("world", myStr.Hello())
  53. val := map[string]MyInterface{"hello":myStr}
  54. str, err := MarshalToString(val)
  55. should.Nil(err)
  56. should.Equal(`{"hello":"world"}`, str)
  57. }
  58. func Test_write_interface(t *testing.T) {
  59. should := require.New(t)
  60. var val interface{}
  61. val = "hello"
  62. str, err := MarshalToString(val)
  63. should.Nil(err)
  64. should.Equal(`"hello"`, str)
  65. }
  66. func Test_read_interface(t *testing.T) {
  67. should := require.New(t)
  68. var val interface{}
  69. err := UnmarshalFromString(`"hello"`, &val)
  70. should.Nil(err)
  71. should.Equal("hello", val)
  72. }
  73. func Test_read_custom_interface(t *testing.T) {
  74. should := require.New(t)
  75. var val MyInterface
  76. RegisterTypeDecoder("jsoniter.MyInterface", func(ptr unsafe.Pointer, iter *Iterator) {
  77. *((*MyInterface)(ptr)) = MyString(iter.ReadString())
  78. })
  79. err := UnmarshalFromString(`"hello"`, &val)
  80. should.Nil(err)
  81. should.Equal("hello", val.Hello())
  82. }