fuzzy_decoder.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package extra
  2. import (
  3. "github.com/json-iterator/go"
  4. "unsafe"
  5. "encoding/json"
  6. )
  7. func RegisterFuzzyDecoders() {
  8. jsoniter.RegisterTypeDecoder("string", &FuzzyStringDecoder{})
  9. jsoniter.RegisterTypeDecoder("int", &FuzzyIntDecoder{})
  10. }
  11. type FuzzyStringDecoder struct {
  12. }
  13. func (decoder *FuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
  14. valueType := iter.WhatIsNext()
  15. switch valueType {
  16. case jsoniter.Number:
  17. var number json.Number
  18. iter.ReadVal(&number)
  19. *((*string)(ptr)) = string(number)
  20. case jsoniter.String:
  21. *((*string)(ptr)) = iter.ReadString()
  22. default:
  23. iter.ReportError("FuzzyStringDecoder", "not number or string")
  24. }
  25. }
  26. type FuzzyIntDecoder struct {
  27. }
  28. func (decoder *FuzzyIntDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
  29. valueType := iter.WhatIsNext()
  30. switch valueType {
  31. case jsoniter.Number:
  32. // use current iterator
  33. case jsoniter.String:
  34. str := iter.ReadString()
  35. iter = iter.Config().BorrowIterator([]byte(str))
  36. defer iter.Config().ReturnIterator(iter)
  37. default:
  38. iter.ReportError("FuzzyIntDecoder", "not number or string")
  39. }
  40. *((*int)(ptr)) = iter.ReadInt()
  41. }