123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- package jsons
- import (
- "strconv"
- "encoding/json"
- //"errors"
- "time"
- )
- // The package implements basic types
- // to be used in structures that can be parsed
- // from the poorly structured JSON. (Like ones that make IDs strings)
- func parseInt(str string, n int) (int64, error) {
- if str == "" {
- return 0, EmptyStringErr
- }
- if str[0] == '"' {
- str = str[1:]
- }
- if str == "" {
- return 0, EmptyStringErr
- }
- if str[len(str)-1] == '"' {
- str = str[:len(str)-1]
- }
- v, err := strconv.ParseInt(str, 10, n)
- if err != nil {
- return 0, err
- }
- return v, nil
- }
- type Int int
- func(ji *Int) UnmarshalJSON(bts []byte) error {
- v, err := parseInt(string(bts), 32)
- if err != nil {
- return err
- }
- *ji = Int(v)
- return nil
- }
- type Int64 int64
- func(ji *Int64) UnmarshalJSON(bts []byte) error {
- v, err := parseInt(string(bts), 64)
- if err != nil {
- return err
- }
- *ji = Int64(v)
- return nil
- }
- type ArrayMap[V any] map[int] V
- func (jam *ArrayMap[V]) UnmarshalJSON(bts []byte) error {
- *jam = make(ArrayMap[V])
- am := *jam
- j := map[string] json.RawMessage{}
- err := json.Unmarshal(bts, &j)
- if err != nil {
- return err
- }
- v := new(V)
- for jk, jv := range j {
- // Getting the key from string.
- k, err := strconv.ParseInt(jk, 10, 32)
- if err != nil {
- return err
- }
- err = json.Unmarshal([]byte(jv), v)
- if err != nil {
- return err
- }
- am[int(k)] = *v
- }
- return nil
- }
- type Timestamp int64
- func (ts *Timestamp) UnmarshalJSON(bts []byte) error {
- i, err := parseInt(string(bts), 64)
- if err != nil {
- return err
- }
- *ts = Timestamp(i)
- return nil
- }
- func (ts Timestamp) Time() time.Time {
- return time.Unix(int64(ts), 0)
- }
|