jsoniter_customize_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package jsoniter
  2. import (
  3. "reflect"
  4. "strconv"
  5. "testing"
  6. "time"
  7. "unsafe"
  8. "github.com/json-iterator/go/require"
  9. )
  10. func Test_customize_type_decoder(t *testing.T) {
  11. RegisterTypeDecoder("time.Time", func(ptr unsafe.Pointer, iter *Iterator) {
  12. t, err := time.ParseInLocation("2006-01-02 15:04:05", iter.ReadString(), time.UTC)
  13. if err != nil {
  14. iter.Error = err
  15. return
  16. }
  17. *((*time.Time)(ptr)) = t
  18. })
  19. defer CleanDecoders()
  20. val := time.Time{}
  21. err := Unmarshal([]byte(`"2016-12-05 08:43:28"`), &val)
  22. if err != nil {
  23. t.Fatal(err)
  24. }
  25. year, month, day := val.Date()
  26. if year != 2016 || month != 12 || day != 5 {
  27. t.Fatal(val)
  28. }
  29. }
  30. func Test_customize_type_encoder(t *testing.T) {
  31. should := require.New(t)
  32. RegisterTypeEncoder("time.Time", func(ptr unsafe.Pointer, stream *Stream) {
  33. t := *((*time.Time)(ptr))
  34. stream.WriteString(t.UTC().Format("2006-01-02 15:04:05"))
  35. })
  36. defer CleanEncoders()
  37. val := time.Unix(0, 0)
  38. str, err := MarshalToString(val)
  39. should.Nil(err)
  40. should.Equal(`"1970-01-01 00:00:00"`, str)
  41. }
  42. func Test_customize_byte_array_encoder(t *testing.T) {
  43. should := require.New(t)
  44. RegisterTypeEncoder("[]uint8", func(ptr unsafe.Pointer, stream *Stream) {
  45. t := *((*[]byte)(ptr))
  46. stream.WriteString(string(t))
  47. })
  48. defer CleanEncoders()
  49. val := []byte("abc")
  50. str, err := MarshalToString(val)
  51. should.Nil(err)
  52. should.Equal(`"abc"`, str)
  53. }
  54. type Tom struct {
  55. field1 string
  56. }
  57. func Test_customize_field_decoder(t *testing.T) {
  58. RegisterFieldDecoder("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) {
  59. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  60. })
  61. defer CleanDecoders()
  62. tom := Tom{}
  63. err := Unmarshal([]byte(`{"field1": 100}`), &tom)
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. }
  68. type TestObject1 struct {
  69. field1 string
  70. }
  71. func Test_customize_field_by_extension(t *testing.T) {
  72. RegisterExtension(func(type_ reflect.Type, field *reflect.StructField) ([]string, DecoderFunc) {
  73. if type_.String() == "jsoniter.TestObject1" && field.Name == "field1" {
  74. return []string{"field-1"}, func(ptr unsafe.Pointer, iter *Iterator) {
  75. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  76. }
  77. }
  78. return nil, nil
  79. })
  80. obj := TestObject1{}
  81. err := Unmarshal([]byte(`{"field-1": 100}`), &obj)
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. if obj.field1 != "100" {
  86. t.Fatal(obj.field1)
  87. }
  88. }