-
Notifications
You must be signed in to change notification settings - Fork 2
/
json.go
82 lines (73 loc) · 1.83 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package util
import (
"encoding/json"
"fmt"
)
// JsonMap 存储任意数据的map
type JsonMap map[string]interface{}
// JsonEncode 将JsonMap转成[]byte
func JsonEncode(m JsonMap) ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
err = fmt.Errorf("JsonEncode err: %s", err.Error())
}
return b, err
}
// JsonDecode 将[]byte转成JsonMap
func JsonDecode(b []byte) (JsonMap, error) {
m := make(JsonMap)
var f interface{}
err := json.Unmarshal(b, &f)
if err != nil {
err = fmt.Errorf("JsonDecode err: %s", err.Error())
} else {
m = f.(map[string]interface{})
}
return m, err
}
// JsonGetInt 从JsonMap中解析出一个int值
func (m JsonMap) JsonGetInt(key string) (int, bool) {
if val, exists := m[key]; exists {
switch val.(type) {
case float64:
return int(val.(float64)), true
case int:
return val.(int), true
}
}
return 0, false
}
// JsonGetUint16 从JsonMap中解析出一个ushort值
func (m JsonMap) JsonGetUint16(key string) (uint16, bool) {
if val, exists := m[key]; exists {
return uint16(val.(float64)), true
}
return uint16(0), false
}
// JsonGetString 从JsonMap中解析出一个string值
func (m JsonMap) JsonGetString(key string) (string, bool) {
if val, exists := m[key]; exists {
return val.(string), true
}
return "", false
}
// JsonGetJsonMap 从JsonMap中解析出一个JsonMap值
func (this JsonMap) JsonGetJsonMap(key string) JsonMap {
if val, exists := this[key]; exists {
switch val.(type) {
case map[string]interface{}:
return JsonMap(val.(map[string]interface{}))
case interface{}:
return val.(JsonMap)
}
}
return JsonMap{}
}
// InterfaceToJsonString 将任意类型的数据,转成json格式的字符串
func InterfaceToJsonString(s interface{}) (string, error) {
byt, err := json.Marshal(s)
if err != nil {
return "", err
}
return string(byt), nil
}