jsoniter_customize_test.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package jsoniter
  2. import (
  3. "encoding/json"
  4. "github.com/stretchr/testify/require"
  5. "strconv"
  6. "testing"
  7. "time"
  8. "unsafe"
  9. "fmt"
  10. "reflect"
  11. )
  12. func Test_customize_type_decoder(t *testing.T) {
  13. RegisterTypeDecoderFunc("time.Time", func(ptr unsafe.Pointer, iter *Iterator) {
  14. t, err := time.ParseInLocation("2006-01-02 15:04:05", iter.ReadString(), time.UTC)
  15. if err != nil {
  16. iter.Error = err
  17. return
  18. }
  19. *((*time.Time)(ptr)) = t
  20. })
  21. defer ConfigDefault.(*frozenConfig).cleanDecoders()
  22. val := time.Time{}
  23. err := Unmarshal([]byte(`"2016-12-05 08:43:28"`), &val)
  24. if err != nil {
  25. t.Fatal(err)
  26. }
  27. year, month, day := val.Date()
  28. if year != 2016 || month != 12 || day != 5 {
  29. t.Fatal(val)
  30. }
  31. }
  32. func Test_customize_type_encoder(t *testing.T) {
  33. should := require.New(t)
  34. RegisterTypeEncoderFunc("time.Time", func(ptr unsafe.Pointer, stream *Stream) {
  35. t := *((*time.Time)(ptr))
  36. stream.WriteString(t.UTC().Format("2006-01-02 15:04:05"))
  37. }, nil)
  38. defer ConfigDefault.(*frozenConfig).cleanEncoders()
  39. val := time.Unix(0, 0)
  40. str, err := MarshalToString(val)
  41. should.Nil(err)
  42. should.Equal(`"1970-01-01 00:00:00"`, str)
  43. }
  44. func Test_customize_byte_array_encoder(t *testing.T) {
  45. ConfigDefault.(*frozenConfig).cleanEncoders()
  46. should := require.New(t)
  47. RegisterTypeEncoderFunc("[]uint8", func(ptr unsafe.Pointer, stream *Stream) {
  48. t := *((*[]byte)(ptr))
  49. stream.WriteString(string(t))
  50. }, nil)
  51. defer ConfigDefault.(*frozenConfig).cleanEncoders()
  52. val := []byte("abc")
  53. str, err := MarshalToString(val)
  54. should.Nil(err)
  55. should.Equal(`"abc"`, str)
  56. }
  57. func Test_customize_float_marshal(t *testing.T) {
  58. should := require.New(t)
  59. json := Config{MarshalFloatWith6Digits: true}.Froze()
  60. str, err := json.MarshalToString(float32(1.23456789))
  61. should.Nil(err)
  62. should.Equal("1.234568", str)
  63. }
  64. type Tom struct {
  65. field1 string
  66. }
  67. func Test_customize_field_decoder(t *testing.T) {
  68. RegisterFieldDecoderFunc("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) {
  69. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  70. })
  71. defer ConfigDefault.(*frozenConfig).cleanDecoders()
  72. tom := Tom{}
  73. err := Unmarshal([]byte(`{"field1": 100}`), &tom)
  74. if err != nil {
  75. t.Fatal(err)
  76. }
  77. }
  78. type TestObject1 struct {
  79. field1 string
  80. }
  81. type testExtension struct {
  82. DummyExtension
  83. }
  84. func (extension *testExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) {
  85. if structDescriptor.Type.String() != "jsoniter.TestObject1" {
  86. return
  87. }
  88. binding := structDescriptor.GetField("field1")
  89. binding.Encoder = &funcEncoder{fun: func(ptr unsafe.Pointer, stream *Stream) {
  90. str := *((*string)(ptr))
  91. val, _ := strconv.Atoi(str)
  92. stream.WriteInt(val)
  93. }}
  94. binding.Decoder = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
  95. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  96. }}
  97. binding.ToNames = []string{"field-1"}
  98. binding.FromNames = []string{"field-1"}
  99. }
  100. func Test_customize_field_by_extension(t *testing.T) {
  101. should := require.New(t)
  102. RegisterExtension(&testExtension{})
  103. obj := TestObject1{}
  104. err := UnmarshalFromString(`{"field-1": 100}`, &obj)
  105. should.Nil(err)
  106. should.Equal("100", obj.field1)
  107. str, err := MarshalToString(obj)
  108. should.Nil(err)
  109. should.Equal(`{"field-1":100}`, str)
  110. }
  111. type timeImplementedMarshaler time.Time
  112. func (obj timeImplementedMarshaler) MarshalJSON() ([]byte, error) {
  113. seconds := time.Time(obj).Unix()
  114. return []byte(strconv.FormatInt(seconds, 10)), nil
  115. }
  116. func Test_marshaler(t *testing.T) {
  117. type TestObject struct {
  118. Field timeImplementedMarshaler
  119. }
  120. should := require.New(t)
  121. val := timeImplementedMarshaler(time.Unix(123, 0))
  122. obj := TestObject{val}
  123. bytes, err := json.Marshal(obj)
  124. should.Nil(err)
  125. should.Equal(`{"Field":123}`, string(bytes))
  126. str, err := MarshalToString(obj)
  127. should.Nil(err)
  128. should.Equal(`{"Field":123}`, str)
  129. }
  130. func Test_marshaler_and_encoder(t *testing.T) {
  131. type TestObject struct {
  132. Field *timeImplementedMarshaler
  133. }
  134. ConfigDefault.(*frozenConfig).cleanEncoders()
  135. should := require.New(t)
  136. RegisterTypeEncoderFunc("jsoniter.timeImplementedMarshaler", func(ptr unsafe.Pointer, stream *Stream) {
  137. stream.WriteString("hello from encoder")
  138. }, nil)
  139. val := timeImplementedMarshaler(time.Unix(123, 0))
  140. obj := TestObject{&val}
  141. bytes, err := json.Marshal(obj)
  142. should.Nil(err)
  143. should.Equal(`{"Field":123}`, string(bytes))
  144. str, err := MarshalToString(obj)
  145. should.Nil(err)
  146. should.Equal(`{"Field":"hello from encoder"}`, str)
  147. }
  148. type ObjectImplementedUnmarshaler int
  149. func (obj *ObjectImplementedUnmarshaler) UnmarshalJSON(s []byte) error {
  150. val, _ := strconv.ParseInt(string(s[1:len(s)-1]), 10, 64)
  151. *obj = ObjectImplementedUnmarshaler(val)
  152. return nil
  153. }
  154. func Test_unmarshaler(t *testing.T) {
  155. should := require.New(t)
  156. var obj ObjectImplementedUnmarshaler
  157. err := json.Unmarshal([]byte(` "100" `), &obj)
  158. should.Nil(err)
  159. should.Equal(100, int(obj))
  160. iter := ParseString(ConfigDefault, ` "100" `)
  161. iter.ReadVal(&obj)
  162. should.Nil(err)
  163. should.Equal(100, int(obj))
  164. }
  165. func Test_unmarshaler_and_decoder(t *testing.T) {
  166. type TestObject struct {
  167. Field *ObjectImplementedUnmarshaler
  168. Field2 string
  169. }
  170. ConfigDefault.(*frozenConfig).cleanDecoders()
  171. should := require.New(t)
  172. RegisterTypeDecoderFunc("jsoniter.ObjectImplementedUnmarshaler", func(ptr unsafe.Pointer, iter *Iterator) {
  173. *(*ObjectImplementedUnmarshaler)(ptr) = 10
  174. iter.Skip()
  175. })
  176. obj := TestObject{}
  177. val := ObjectImplementedUnmarshaler(0)
  178. obj.Field = &val
  179. err := json.Unmarshal([]byte(`{"Field":"100"}`), &obj)
  180. should.Nil(err)
  181. should.Equal(100, int(*obj.Field))
  182. err = Unmarshal([]byte(`{"Field":"100"}`), &obj)
  183. should.Nil(err)
  184. should.Equal(10, int(*obj.Field))
  185. }
  186. type tmString string
  187. type tmStruct struct {
  188. String tmString
  189. }
  190. func (s tmStruct) MarshalJSON() ([]byte, error) {
  191. var b []byte
  192. b = append(b, '"')
  193. b = append(b, s.String...)
  194. b = append(b, '"')
  195. return b, nil
  196. }
  197. func Test_marshaler_on_struct(t *testing.T) {
  198. fixed := tmStruct{"hello"}
  199. //json.Marshal(fixed)
  200. Marshal(fixed)
  201. }
  202. type withChan struct {
  203. F2 chan []byte
  204. }
  205. func (q withChan) MarshalJSON() ([]byte, error) {
  206. return []byte(`""`), nil
  207. }
  208. func (q *withChan) UnmarshalJSON(value []byte) error {
  209. return nil
  210. }
  211. func Test_marshal_json_with_chan(t *testing.T) {
  212. type TestObject struct {
  213. F1 withChan
  214. }
  215. should := require.New(t)
  216. output, err := MarshalToString(TestObject{})
  217. should.Nil(err)
  218. should.Equal(`{"F1":""}`, output)
  219. }
  220. type withTime struct {
  221. time.Time
  222. }
  223. func (t *withTime) UnmarshalJSON(b []byte) error {
  224. return nil
  225. }
  226. func (t withTime) MarshalJSON() ([]byte, error) {
  227. return []byte(`"fake"`), nil
  228. }
  229. func Test_marshal_json_with_time(t *testing.T) {
  230. type S1 struct {
  231. F1 withTime
  232. F2 *withTime
  233. }
  234. type TestObject struct {
  235. TF1 S1
  236. }
  237. should := require.New(t)
  238. obj := TestObject{
  239. S1{
  240. F1: withTime{
  241. time.Unix(0, 0),
  242. },
  243. F2: &withTime{
  244. time.Unix(0, 0),
  245. },
  246. },
  247. }
  248. output, err := json.Marshal(obj)
  249. should.Nil(err)
  250. should.Equal(`{"TF1":{"F1":"fake","F2":"fake"}}`, string(output))
  251. output, err = Marshal(obj)
  252. should.Nil(err)
  253. should.Equal(`{"TF1":{"F1":"fake","F2":"fake"}}`, string(output))
  254. obj = TestObject{}
  255. should.Nil(json.Unmarshal([]byte(`{"TF1":{"F1":"fake","F2":"fake"}}`), &obj))
  256. should.NotNil(obj.TF1.F2)
  257. obj = TestObject{}
  258. should.Nil(Unmarshal([]byte(`{"TF1":{"F1":"fake","F2":"fake"}}`), &obj))
  259. should.NotNil(obj.TF1.F2)
  260. }
  261. func Test_unmarshal_empty_interface_as_int64(t *testing.T) {
  262. var obj interface{}
  263. RegisterTypeDecoderFunc("interface {}", func(ptr unsafe.Pointer, iter *Iterator) {
  264. switch iter.WhatIsNext() {
  265. case NumberValue:
  266. *(*interface{})(ptr) = iter.ReadInt64()
  267. default:
  268. *(*interface{})(ptr) = iter.Read()
  269. }
  270. })
  271. should := require.New(t)
  272. Unmarshal([]byte("100"), &obj)
  273. should.Equal(int64(100), obj)
  274. Unmarshal([]byte(`"hello"`), &obj)
  275. should.Equal("hello", obj)
  276. var arr []interface{}
  277. Unmarshal([]byte("[100]"), &arr)
  278. should.Equal(int64(100), arr[0])
  279. }