jsoniter_interface_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. type MyInterface interface {
  22. Hello() string
  23. }
  24. type MyString string
  25. func (ms MyString) Hello() string {
  26. return string(ms)
  27. }
  28. func Test_write_map_of_custom_interface(t *testing.T) {
  29. should := require.New(t)
  30. myStr := MyString("world")
  31. should.Equal("world", myStr.Hello())
  32. val := map[string]MyInterface{"hello":myStr}
  33. str, err := MarshalToString(val)
  34. should.Nil(err)
  35. should.Equal(`{"hello":"world"}`, str)
  36. }
  37. func Test_write_interface(t *testing.T) {
  38. should := require.New(t)
  39. var val interface{}
  40. val = "hello"
  41. str, err := MarshalToString(val)
  42. should.Nil(err)
  43. should.Equal(`"hello"`, str)
  44. }
  45. func Test_read_interface(t *testing.T) {
  46. should := require.New(t)
  47. var val interface{}
  48. err := UnmarshalFromString(`"hello"`, &val)
  49. should.Nil(err)
  50. should.Equal("hello", val)
  51. }
  52. func Test_read_custom_interface(t *testing.T) {
  53. should := require.New(t)
  54. var val MyInterface
  55. RegisterTypeDecoder("jsoniter.MyInterface", func(ptr unsafe.Pointer, iter *Iterator) {
  56. *((*MyInterface)(ptr)) = MyString(iter.ReadString())
  57. })
  58. err := UnmarshalFromString(`"hello"`, &val)
  59. should.Nil(err)
  60. should.Equal("hello", val.Hello())
  61. }