-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_types.go
138 lines (111 loc) · 2.24 KB
/
json_types.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package toast
import (
"encoding/json"
"strconv"
"time"
)
type Date struct {
time.Time
}
func (d Date) MarshalSchema() string {
return d.Time.Format("20060102")
}
func (d Date) IsEmpty() bool {
return d.Time.IsZero()
}
type DateTime struct {
time.Time
}
func (d *Date) MarshalJSON() ([]byte, error) {
if d.Time.IsZero() {
return json.Marshal(nil)
}
f := d.Time.Format("20060102")
i, err := strconv.Atoi(f)
if err != nil {
return []byte{}, err
}
return json.Marshal(i)
}
func (d *Date) UnmarshalJSON(text []byte) (err error) {
var i int
err = json.Unmarshal(text, &i)
if err == nil && i != 0 {
d.Time, err = time.Parse("20060102", strconv.Itoa(i))
return err
}
var value string
err = json.Unmarshal(text, &value)
if err != nil {
return err
}
if value == "" {
return nil
}
// first try standard date
d.Time, err = time.Parse(time.RFC3339, value)
if err == nil {
return nil
}
d.Time, err = time.Parse("2006-01-02", value)
if err == nil {
return nil
}
d.Time, err = time.Parse("2006-01-02T15:04:05", value)
return err
}
func (d DateTime) MarshalSchema() string {
return d.Time.Format("2006-01-02T15:04:05.000-07:00")
}
func (dt *DateTime) MarshalJSON() ([]byte, error) {
if dt.Time.IsZero() {
return json.Marshal(nil)
}
return json.Marshal(dt.Time.Format("2006-01-02T15:04:05.000-0700"))
}
func (dt *DateTime) UnmarshalJSON(text []byte) (err error) {
var value string
err = json.Unmarshal(text, &value)
if err != nil {
return err
}
if value == "" {
return nil
}
// first try standard date
dt.Time, err = time.Parse(time.RFC3339, value)
if err == nil {
return nil
}
dt.Time, err = time.Parse("2006-01-02T15:04:05.000-0700", value)
return err
}
type Number float64
func (i *Number) UnmarshalJSON(data []byte) error {
realNumber := 0.0
err := json.Unmarshal(data, &realNumber)
if err == nil {
*i = Number(realNumber)
return nil
}
// error, so maybe it isn't an int
str := ""
err = json.Unmarshal(data, &str)
if err != nil {
return err
}
if str == "" {
*i = 0
return nil
}
realNumber, err = strconv.ParseFloat(str, 64)
if err != nil {
return err
}
i2 := Number(realNumber)
*i = i2
return nil
}
func (i Number) MarshalJSON() ([]byte, error) {
return json.Marshal(int(i))
}