-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_marshal.go
51 lines (48 loc) · 1.26 KB
/
json_marshal.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
package utils
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
func JsonMarshal(v interface{}) ([]byte, error) {
vv := reflect.ValueOf(v)
if vv.Kind() == reflect.Slice {
items := make([]string, 0, vv.Len())
for i := 0; i < vv.Len(); i++ {
itemBytes, err := JsonMarshal(vv.Index(i).Interface())
if err != nil {
return nil, err
}
items = append(items, string(itemBytes))
}
data := fmt.Sprintf("[%s]", strings.Join(items, ","))
return []byte(data), nil
} else if vv.Kind() == reflect.Map {
items := make([]string, 0, vv.Len())
for _, mapKey := range vv.MapKeys() {
mapValue := vv.MapIndex(mapKey)
jsonKey, err := JsonMarshal(mapKey.Interface())
if err != nil {
return nil, err
}
jsonVal, err := JsonMarshal(mapValue.Interface())
if err != nil {
return nil, err
}
items = append(items, fmt.Sprintf("%s:%s", string(jsonKey), string(jsonVal)))
}
data := fmt.Sprintf("{%s}", strings.Join(items, ","))
return []byte(data), nil
} else {
if m, ok := v.(proto.Message); ok {
return protojson.Marshal(m)
} else if s, ok := v.(fmt.Stringer); ok {
return json.Marshal(s.String())
} else {
return json.Marshal(v)
}
}
}