jsoniter_customize_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package jsoniter
  2. import (
  3. "reflect"
  4. "strconv"
  5. "testing"
  6. "time"
  7. "unsafe"
  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 CleanDecoders()
  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 CleanDecoders()
  37. tom := Tom{}
  38. err := Unmarshal([]byte(`{"field1": 100}`), &tom)
  39. if err != nil {
  40. t.Fatal(err)
  41. }
  42. }
  43. type TestObject1 struct {
  44. field1 string
  45. }
  46. func Test_customize_field_by_extension(t *testing.T) {
  47. RegisterExtension(func(type_ reflect.Type, field *reflect.StructField) ([]string, DecoderFunc) {
  48. if type_.String() == "jsoniter.TestObject1" && field.Name == "field1" {
  49. return []string{"field-1"}, func(ptr unsafe.Pointer, iter *Iterator) {
  50. *((*string)(ptr)) = strconv.Itoa(iter.ReadInt())
  51. }
  52. }
  53. return nil, nil
  54. })
  55. obj := TestObject1{}
  56. err := Unmarshal([]byte(`{"field-1": 100}`), &obj)
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. if obj.field1 != "100" {
  61. t.Fatal(obj.field1)
  62. }
  63. }