-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
64 lines (51 loc) · 1.26 KB
/
json.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
package goutility
import (
"encoding/json"
"fmt"
"strings"
"time"
)
func MarshalToJSON(v interface{}) ([]byte, ErrorTypeInterface) {
rawData, error := json.Marshal(v)
if error != nil {
return nil, MakeMashalError(v, error)
}
return rawData, nil
}
func MarshalIndentToJSON(v interface{}, prefix string, indent string) ([]byte, ErrorTypeInterface) {
rawData, error := json.MarshalIndent(v, prefix, indent)
if error != nil {
return nil, MakeMashalError(v, error)
}
return rawData, nil
}
func UnmarshalFromJSON(data []byte, v interface{}) ErrorTypeInterface {
error := json.Unmarshal(data, v)
if error != nil {
return MakeUnmashalError(v, error)
}
return nil
}
// region JSON Safe Time
type JSONSafeTime struct {
time.Time
}
func (this *JSONSafeTime) Format() string {
return time.RFC3339Nano
}
func (this *JSONSafeTime) UnmarshalJSON(b []byte) (err error) {
string := strings.Trim(string(b), "\"")
if string == "null" {
this.Time = time.Time{}
return
}
this.Time, err = time.Parse(this.Format(), string)
return
}
func (this *JSONSafeTime) MarshalJSON() ([]byte, error) {
if this.Time.UnixNano() == (time.Time{}).UnixNano() {
return []byte("null"), nil
}
return []byte(fmt.Sprintf("\"%s\"", this.Time.Format(this.Format()))), nil
}
// endregion