main.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package jsons
  2. import (
  3. "strconv"
  4. "encoding/json"
  5. //"errors"
  6. "time"
  7. )
  8. // The package implements basic types
  9. // to be used in structures that can be parsed
  10. // from the poorly structured JSON. (Like ones that make IDs strings)
  11. func parseInt(str string, n int) (int64, error) {
  12. if str == "" {
  13. return 0, EmptyStringErr
  14. }
  15. if str[0] == '"' {
  16. str = str[1:]
  17. }
  18. if str == "" {
  19. return 0, EmptyStringErr
  20. }
  21. if str[len(str)-1] == '"' {
  22. str = str[:len(str)-1]
  23. }
  24. v, err := strconv.ParseInt(str, 10, n)
  25. if err != nil {
  26. return 0, err
  27. }
  28. return v, nil
  29. }
  30. type Int int
  31. func(ji *Int) UnmarshalJSON(bts []byte) error {
  32. v, err := parseInt(string(bts), 32)
  33. if err != nil {
  34. return err
  35. }
  36. *ji = Int(v)
  37. return nil
  38. }
  39. type Int64 int64
  40. func(ji *Int64) UnmarshalJSON(bts []byte) error {
  41. v, err := parseInt(string(bts), 64)
  42. if err != nil {
  43. return err
  44. }
  45. *ji = Int64(v)
  46. return nil
  47. }
  48. type ArrayMap[V any] map[int] V
  49. func (jam *ArrayMap[V]) UnmarshalJSON(bts []byte) error {
  50. *jam = make(ArrayMap[V])
  51. am := *jam
  52. j := map[string] json.RawMessage{}
  53. err := json.Unmarshal(bts, &j)
  54. if err != nil {
  55. return err
  56. }
  57. v := new(V)
  58. for jk, jv := range j {
  59. // Getting the key from string.
  60. k, err := strconv.ParseInt(jk, 10, 32)
  61. if err != nil {
  62. return err
  63. }
  64. err = json.Unmarshal([]byte(jv), v)
  65. if err != nil {
  66. return err
  67. }
  68. am[int(k)] = *v
  69. }
  70. return nil
  71. }
  72. type Timestamp int64
  73. func (ts *Timestamp) UnmarshalJSON(bts []byte) error {
  74. i, err := parseInt(string(bts), 64)
  75. if err != nil {
  76. return err
  77. }
  78. *ts = Timestamp(i)
  79. return nil
  80. }
  81. func (ts Timestamp) Time() time.Time {
  82. return time.Unix(int64(ts), 0)
  83. }