-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.go
113 lines (99 loc) · 2.13 KB
/
process.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
package model
import (
"errors"
"strconv"
"time"
"github.com/sohaha/zlsgo/zjson"
"github.com/sohaha/zlsgo/zstring"
"github.com/sohaha/zlsgo/ztime"
"github.com/sohaha/zlsgo/ztype"
)
func jsonMarshalProcess(isArray bool) func(s interface{}) (string, error) {
return func(s interface{}) (j string, err error) {
defer func() {
if j == "" {
if isArray {
j = "[]"
} else {
j = "{}"
}
}
}()
switch v := s.(type) {
case string:
if zjson.Valid(v) {
return v, nil
}
return
case ztype.Type:
s = v.Value()
}
var jb []byte
jb, err = zjson.Marshal(s)
if err != nil {
return
}
j = zstring.Bytes2String(jb)
return
}
}
func jsonUnmarshalProcess(isArray bool) func(s string) (interface{}, error) {
return func(s string) (interface{}, error) {
j := zjson.Parse(s)
if s == "" {
if isArray {
return ztype.Maps{}, nil
}
return ztype.Map{}, nil
}
if !j.Exists() {
return nil, errors.New("json parse error")
}
if j.IsArray() {
return j.Slice().Value(), nil
}
return j.Map(), nil
}
}
func boolMarshalProcess(s interface{}) (string, error) {
return strconv.Itoa(ztype.ToInt(s)), nil
}
func boolUnmarshalProcess(s string) (interface{}, error) {
return ztype.ToBool(s), nil
}
func dateMarshalProcess(format string) func(v interface{}) (string, error) {
return func(v interface{}) (string, error) {
if t, ok := v.(time.Time); ok {
return ztime.FormatTime(t, format), nil
}
s := ztype.ToString(v)
if s == "" {
return "", nil
}
t, err := ztime.Parse(s)
if err != nil {
timestamp, err := strconv.Atoi(s)
if err == nil {
return ztime.FormatTimestamp(int64(timestamp), format), nil
}
return "", err
}
return ztime.FormatTime(t, format), nil
}
}
func dateUnmarshalProcess(format string) func(v string) (interface{}, error) {
return func(v string) (interface{}, error) {
if v == "" {
return "", nil
}
timestamp, err := strconv.Atoi(v)
if err == nil {
return ztime.FormatTimestamp(int64(timestamp), format), nil
}
t, err := ztime.Parse(v)
if err != nil {
return "", err
}
return ztime.FormatTime(t, format), nil
}
}