-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
93 lines (79 loc) · 2.08 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
83
84
85
86
87
88
89
90
91
92
93
package json
import (
"bytes"
"errors"
"unsafe"
"github.com/fufuok/bytespool"
"github.com/fufuok/utils"
)
type RawMessage []byte
// MarshalJSON returns m as the JSON encoding of m.
func (m RawMessage) MarshalJSON() ([]byte, error) {
if m == nil {
return []byte("null"), nil
}
return m, nil
}
// UnmarshalJSON sets *m to a copy of data.
func (m *RawMessage) UnmarshalJSON(data []byte) error {
if m == nil {
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
}
*m = append((*m)[0:0], data...)
return nil
}
// Copy returns a copy of m.
func (m RawMessage) Copy() []byte {
return bytespool.NewBytes(m)
}
// MustJSONIndent 转 json 返回 []byte
func MustJSONIndent(v any) []byte {
js, _ := MarshalIndent(v, "", " ")
return js
}
// MustJSONIndentString 转 json 返回 string
func MustJSONIndentString(v any) string {
js := MustJSONIndent(v)
return *(*string)(unsafe.Pointer(&js))
}
// MustJSON 转 json 返回 []byte
func MustJSON(v any) []byte {
js, _ := Marshal(v)
return js
}
// MustJSONString 转 json 返回 string
func MustJSONString(v any) string {
js := MustJSON(v)
return *(*string)(unsafe.Pointer(&js))
}
// MustJSONUnEscapeIndent 转 json 返回 []byte, 不转义 ( '&', '<', '>' )
func MustJSONUnEscapeIndent(v any) []byte {
buf := bytes.NewBuffer(nil)
enc := NewEncoder(buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(v); err != nil {
return nil
}
return buf.Bytes()[:buf.Len()-1]
}
// MustJSONUnEscapeIndentString 转 json 返回 string, 不转义 ( '&', '<', '>' )
func MustJSONUnEscapeIndentString(v any) string {
js := MustJSONUnEscapeIndent(v)
return utils.B2S(js)
}
// MustJSONUnEscape 转 json 返回 []byte, 不转义 ( '&', '<', '>' )
func MustJSONUnEscape(v any) []byte {
buf := bytes.NewBuffer(nil)
enc := NewEncoder(buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return nil
}
return buf.Bytes()[:buf.Len()-1]
}
// MustJSONUnEscapeString 转 json 返回 string, 不转义 ( '&', '<', '>' )
func MustJSONUnEscapeString(v any) string {
js := MustJSONUnEscape(v)
return utils.B2S(js)
}