jsoniter_customize_test.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. package jsoniter
  2. import (
  3. "encoding/json"
  4. "github.com/json-iterator/go/require"
  5. "strconv"
  6. "testing"
  7. "time"
  8. "unsafe"
  9. )
  10. func Test_customize_type_decoder(t *testing.T) {
  11. RegisterTypeDecoderFunc("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 ConfigDefault.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. RegisterTypeEncoderFunc("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. }, nil)
  36. defer ConfigDefault.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. ConfigDefault.cleanEncoders()
  44. should := require.New(t)
  45. RegisterTypeEncoderFunc("[]uint8", func(ptr unsafe.Pointer, stream *Stream) {
  46. t := *((*[]byte)(ptr))
  47. stream.WriteString(string(t))
  48. }, nil)
  49. defer ConfigDefault.cleanEncoders()
  50. val := []byte("abc")
  51. str, err := MarshalToString(val)
  52. should.Nil(err)
  53. should.Equal(`"abc"`, str)
  54. }
  55. func Test_customize_float_marshal(t *testing.T) {
  56. should := require.New(t)
  57. json := Config{MarshalFloatWith6Digits: true}.Froze()
  58. str, err := json.MarshalToString(float32(1.23456789))
  59. should.Nil(err)
  60. should.Equal("1.234568", str)
  61. }
  62. type Tom struct {
  63. field1 string
  64. }
  65. func Test_customize_field_decoder(t *testing.T) {
  66. RegisterFieldDecoderFunc("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) {
  67. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  68. })
  69. defer ConfigDefault.cleanDecoders()
  70. tom := Tom{}
  71. err := Unmarshal([]byte(`{"field1": 100}`), &tom)
  72. if err != nil {
  73. t.Fatal(err)
  74. }
  75. }
  76. type TestObject1 struct {
  77. field1 string
  78. }
  79. type testExtension struct {
  80. DummyExtension
  81. }
  82. func (extension *testExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) {
  83. if structDescriptor.Type.String() != "jsoniter.TestObject1" {
  84. return
  85. }
  86. binding := structDescriptor.Fields["field1"]
  87. binding.Encoder = &funcEncoder{fun: func(ptr unsafe.Pointer, stream *Stream) {
  88. str := *((*string)(ptr))
  89. val, _ := strconv.Atoi(str)
  90. stream.WriteInt(val)
  91. }}
  92. binding.Decoder = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
  93. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  94. }}
  95. binding.ToNames = []string{"field-1"}
  96. binding.FromNames = []string{"field-1"}
  97. }
  98. func Test_customize_field_by_extension(t *testing.T) {
  99. should := require.New(t)
  100. RegisterExtension(&testExtension{})
  101. obj := TestObject1{}
  102. err := UnmarshalFromString(`{"field-1": 100}`, &obj)
  103. should.Nil(err)
  104. should.Equal("100", obj.field1)
  105. str, err := MarshalToString(obj)
  106. should.Nil(err)
  107. should.Equal(`{"field-1":100}`, str)
  108. }
  109. //func Test_unexported_fields(t *testing.T) {
  110. // jsoniter := Config{SupportUnexportedStructFields: true}.Froze()
  111. // should := require.New(t)
  112. // type TestObject struct {
  113. // field1 string
  114. // field2 string `json:"field-2"`
  115. // }
  116. // obj := TestObject{}
  117. // obj.field1 = "hello"
  118. // should.Nil(jsoniter.UnmarshalFromString(`{}`, &obj))
  119. // should.Equal("hello", obj.field1)
  120. // should.Nil(jsoniter.UnmarshalFromString(`{"field1": "world", "field-2": "abc"}`, &obj))
  121. // should.Equal("world", obj.field1)
  122. // should.Equal("abc", obj.field2)
  123. // str, err := jsoniter.MarshalToString(obj)
  124. // should.Nil(err)
  125. // should.Contains(str, `"field-2":"abc"`)
  126. //}
  127. type ObjectImplementedMarshaler int
  128. func (obj *ObjectImplementedMarshaler) MarshalJSON() ([]byte, error) {
  129. return []byte(`"hello"`), nil
  130. }
  131. func Test_marshaler(t *testing.T) {
  132. type TestObject struct {
  133. Field *ObjectImplementedMarshaler
  134. }
  135. should := require.New(t)
  136. val := ObjectImplementedMarshaler(100)
  137. obj := TestObject{&val}
  138. bytes, err := json.Marshal(obj)
  139. should.Nil(err)
  140. should.Equal(`{"Field":"hello"}`, string(bytes))
  141. str, err := MarshalToString(obj)
  142. should.Nil(err)
  143. should.Equal(`{"Field":"hello"}`, str)
  144. }
  145. func Test_marshaler_and_encoder(t *testing.T) {
  146. type TestObject struct {
  147. Field *ObjectImplementedMarshaler
  148. }
  149. ConfigDefault.cleanEncoders()
  150. should := require.New(t)
  151. RegisterTypeEncoderFunc("jsoniter.ObjectImplementedMarshaler", func(ptr unsafe.Pointer, stream *Stream) {
  152. stream.WriteString("hello from encoder")
  153. }, nil)
  154. val := ObjectImplementedMarshaler(100)
  155. obj := TestObject{&val}
  156. bytes, err := json.Marshal(obj)
  157. should.Nil(err)
  158. should.Equal(`{"Field":"hello"}`, string(bytes))
  159. str, err := MarshalToString(obj)
  160. should.Nil(err)
  161. should.Equal(`{"Field":"hello from encoder"}`, str)
  162. }
  163. type ObjectImplementedUnmarshaler int
  164. func (obj *ObjectImplementedUnmarshaler) UnmarshalJSON([]byte) error {
  165. *obj = 100
  166. return nil
  167. }
  168. func Test_unmarshaler(t *testing.T) {
  169. type TestObject struct {
  170. Field *ObjectImplementedUnmarshaler
  171. Field2 string
  172. }
  173. should := require.New(t)
  174. obj := TestObject{}
  175. val := ObjectImplementedUnmarshaler(0)
  176. obj.Field = &val
  177. err := json.Unmarshal([]byte(`{"Field":"hello"}`), &obj)
  178. should.Nil(err)
  179. should.Equal(100, int(*obj.Field))
  180. err = Unmarshal([]byte(`{"Field":"hello"}`), &obj)
  181. should.Nil(err)
  182. should.Equal(100, int(*obj.Field))
  183. }
  184. func Test_unmarshaler_and_decoder(t *testing.T) {
  185. type TestObject struct {
  186. Field *ObjectImplementedUnmarshaler
  187. Field2 string
  188. }
  189. ConfigDefault.cleanDecoders()
  190. should := require.New(t)
  191. RegisterTypeDecoderFunc("jsoniter.ObjectImplementedUnmarshaler", func(ptr unsafe.Pointer, iter *Iterator) {
  192. *(*ObjectImplementedUnmarshaler)(ptr) = 10
  193. iter.Skip()
  194. })
  195. obj := TestObject{}
  196. val := ObjectImplementedUnmarshaler(0)
  197. obj.Field = &val
  198. err := json.Unmarshal([]byte(`{"Field":"hello"}`), &obj)
  199. should.Nil(err)
  200. should.Equal(100, int(*obj.Field))
  201. err = Unmarshal([]byte(`{"Field":"hello"}`), &obj)
  202. should.Nil(err)
  203. should.Equal(10, int(*obj.Field))
  204. }
  205. type tmString string
  206. type tmStruct struct {
  207. String tmString
  208. }
  209. func (s tmStruct) MarshalJSON() ([]byte, error) {
  210. var b []byte
  211. b = append(b, '"')
  212. b = append(b, s.String...)
  213. b = append(b, '"')
  214. return b, nil
  215. }
  216. func Test_marshaler_on_struct(t *testing.T) {
  217. fixed := tmStruct{"hello"}
  218. //json.Marshal(fixed)
  219. Marshal(fixed)
  220. }