-
Notifications
You must be signed in to change notification settings - Fork 0
/
serializer.go
60 lines (56 loc) · 1.66 KB
/
serializer.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
package fastjson
import (
log "github.com/sirupsen/logrus"
"reflect"
"strings"
)
func ToJSONB(v interface{}) []byte {
if bytes, err := json.Marshal(v); err != nil {
log.Warning(err)
return nil
} else {
return bytes
}
}
func ToJSONBv2(v interface{}, serializer *JSONSerializerFeature) []byte {
if serializer.MethodValue {
var t = reflect.TypeOf(v)
var kind = t.Kind()
if kind == reflect.Ptr {
var ve = reflect.ValueOf(v).Elem()
var fieldsNum = ve.NumField()
var params = []reflect.Value{reflect.ValueOf(v)}
for i := 0; i < fieldsNum; i++ {
var field = t.Elem().Field(0)
var tag = field.Tag
var methodName, ok = tag.Lookup("method")
if !ok || methodName == "-" {
continue
}
if methodName == "" {
methodName = "Get" + field.Name
} else if strings.HasPrefix(methodName, "-") {
methodName = methodName[1:] + field.Name
}
var method, exist = t.MethodByName(methodName)
if !exist {
continue
}
var vals = method.Func.Call(params)
if len(vals) != 1 {
continue
}
ve.Field(i).Set(vals[0]) // panic if type not compatible
}
}
}
return ToJSONB(v)
}
func ToJSON(v interface{}) string {
if s, err := json.MarshalToString(v); err != nil {
log.Warning(err)
return ""
} else {
return s
}
}