jsoniter_customize_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package jsoniter
  2. import (
  3. "testing"
  4. "time"
  5. "unsafe"
  6. "strconv"
  7. "reflect"
  8. )
  9. func Test_customize_type_decoder(t *testing.T) {
  10. RegisterTypeDecoder("time.Time", func(ptr unsafe.Pointer, iter *Iterator) {
  11. t, err := time.ParseInLocation("2006-01-02 15:04:05", iter.ReadString(), time.UTC)
  12. if err != nil {
  13. iter.Error = err
  14. return
  15. }
  16. *((*time.Time)(ptr)) = t
  17. })
  18. defer ClearDecoders()
  19. val := time.Time{}
  20. err := Unmarshal([]byte(`"2016-12-05 08:43:28"`), &val)
  21. if err != nil {
  22. t.Fatal(err)
  23. }
  24. year, month, day := val.Date()
  25. if year != 2016 || month != 12 || day != 5 {
  26. t.Fatal(val)
  27. }
  28. }
  29. type Tom struct {
  30. field1 string
  31. }
  32. func Test_customize_field_decoder(t *testing.T) {
  33. RegisterFieldDecoder("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) {
  34. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  35. })
  36. defer ClearDecoders()
  37. tom := Tom{}
  38. err := Unmarshal([]byte(`{"field1": 100}`), &tom)
  39. if err != nil {
  40. t.Fatal(err)
  41. }
  42. }
  43. func Test_customize_field_decoder_factory(t *testing.T) {
  44. RegisterFieldCustomizer(func(type_ reflect.Type, field *reflect.StructField) ([]string, DecoderFunc) {
  45. if (type_.String() == "jsoniter.Tom" && field.Name == "field1") {
  46. return []string{"field-1"}, func(ptr unsafe.Pointer, iter *Iterator) {
  47. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  48. }
  49. }
  50. return nil, nil
  51. })
  52. tom := Tom{}
  53. err := Unmarshal([]byte(`{"field-1": 100}`), &tom)
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. if tom.field1 != "100" {
  58. t.Fatal(tom.field1)
  59. }
  60. }