jsoniter_customize_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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.GetField("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 timeImplementedMarshaler time.Time
  128. func (obj timeImplementedMarshaler) MarshalJSON() ([]byte, error) {
  129. seconds := time.Time(obj).Unix()
  130. return []byte(strconv.FormatInt(seconds, 10)), nil
  131. }
  132. func Test_marshaler(t *testing.T) {
  133. type TestObject struct {
  134. Field timeImplementedMarshaler
  135. }
  136. should := require.New(t)
  137. val := timeImplementedMarshaler(time.Unix(123, 0))
  138. obj := TestObject{val}
  139. bytes, err := json.Marshal(obj)
  140. should.Nil(err)
  141. should.Equal(`{"Field":123}`, string(bytes))
  142. str, err := MarshalToString(obj)
  143. should.Nil(err)
  144. should.Equal(`{"Field":123}`, str)
  145. }
  146. func Test_marshaler_and_encoder(t *testing.T) {
  147. type TestObject struct {
  148. Field *timeImplementedMarshaler
  149. }
  150. ConfigDefault.cleanEncoders()
  151. should := require.New(t)
  152. RegisterTypeEncoderFunc("jsoniter.timeImplementedMarshaler", func(ptr unsafe.Pointer, stream *Stream) {
  153. stream.WriteString("hello from encoder")
  154. }, nil)
  155. val := timeImplementedMarshaler(time.Unix(123, 0))
  156. obj := TestObject{&val}
  157. bytes, err := json.Marshal(obj)
  158. should.Nil(err)
  159. should.Equal(`{"Field":123}`, string(bytes))
  160. str, err := MarshalToString(obj)
  161. should.Nil(err)
  162. should.Equal(`{"Field":"hello from encoder"}`, str)
  163. }
  164. type ObjectImplementedUnmarshaler int
  165. func (obj *ObjectImplementedUnmarshaler) UnmarshalJSON([]byte) error {
  166. *obj = 100
  167. return nil
  168. }
  169. func Test_unmarshaler(t *testing.T) {
  170. type TestObject struct {
  171. Field *ObjectImplementedUnmarshaler
  172. Field2 string
  173. }
  174. should := require.New(t)
  175. obj := TestObject{}
  176. val := ObjectImplementedUnmarshaler(0)
  177. obj.Field = &val
  178. err := json.Unmarshal([]byte(`{"Field":"hello"}`), &obj)
  179. should.Nil(err)
  180. should.Equal(100, int(*obj.Field))
  181. err = Unmarshal([]byte(`{"Field":"hello"}`), &obj)
  182. should.Nil(err)
  183. should.Equal(100, int(*obj.Field))
  184. }
  185. func Test_unmarshaler_and_decoder(t *testing.T) {
  186. type TestObject struct {
  187. Field *ObjectImplementedUnmarshaler
  188. Field2 string
  189. }
  190. ConfigDefault.cleanDecoders()
  191. should := require.New(t)
  192. RegisterTypeDecoderFunc("jsoniter.ObjectImplementedUnmarshaler", func(ptr unsafe.Pointer, iter *Iterator) {
  193. *(*ObjectImplementedUnmarshaler)(ptr) = 10
  194. iter.Skip()
  195. })
  196. obj := TestObject{}
  197. val := ObjectImplementedUnmarshaler(0)
  198. obj.Field = &val
  199. err := json.Unmarshal([]byte(`{"Field":"hello"}`), &obj)
  200. should.Nil(err)
  201. should.Equal(100, int(*obj.Field))
  202. err = Unmarshal([]byte(`{"Field":"hello"}`), &obj)
  203. should.Nil(err)
  204. should.Equal(10, int(*obj.Field))
  205. }
  206. type tmString string
  207. type tmStruct struct {
  208. String tmString
  209. }
  210. func (s tmStruct) MarshalJSON() ([]byte, error) {
  211. var b []byte
  212. b = append(b, '"')
  213. b = append(b, s.String...)
  214. b = append(b, '"')
  215. return b, nil
  216. }
  217. func Test_marshaler_on_struct(t *testing.T) {
  218. fixed := tmStruct{"hello"}
  219. //json.Marshal(fixed)
  220. Marshal(fixed)
  221. }