-
Notifications
You must be signed in to change notification settings - Fork 3
/
marshal.go
executable file
·55 lines (45 loc) · 1.2 KB
/
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
52
53
54
55
package jsoniterKit
import "github.com/richelieu-yang/chimera/v2/src/core/strKit"
// Marshal 序列化(可选配置: api && indent).
/*
@param obj 可以为nil || ""
e.g.
(nil) => []byte("null"), nil
("") => []byte("\"\""), nil
*/
func Marshal(obj interface{}, options ...JsonOption) ([]byte, error) {
opts := loadOptions(options...)
if strKit.IsAllEmpty(opts.prefix, opts.indent) {
return opts.api.Marshal(obj)
}
return opts.api.MarshalIndent(obj, opts.prefix, opts.indent)
}
// MarshalToString 序列化为json字符串(可选配置: api && indent).
/*
@param obj 可以为nil || ""
e.g.
(nil) => "null", nil
("") => "\"\"", nil
e.g.1
m := map[string]interface{}{
"a": "0",
"b": "1",
}
str, _ := jsonKit.MarshalToString(m)
fmt.Println(str)
// {"a":"0","b":"1"}
str, _ = jsonKit.MarshalToString(m, jsonKit.WithIndent(" "))
fmt.Println(str)
//{
// "a": "0",
// "b": "1"
//}
*/
func MarshalToString(obj interface{}, options ...JsonOption) (string, error) {
opts := loadOptions(options...)
if strKit.IsAllEmpty(opts.prefix, opts.indent) {
return opts.api.MarshalToString(obj)
}
data, err := opts.api.MarshalIndent(obj, opts.prefix, opts.indent)
return string(data), err
}