This commit is contained in:
sprov
2021-06-06 22:37:10 +08:00
parent 810dad53d5
commit 3d7192d0f6
29 changed files with 1131 additions and 199 deletions

View File

@@ -1,37 +1,24 @@
package json_util
import (
"encoding/json"
"reflect"
"x-ui/util/reflect_util"
"errors"
)
/*
MarshalJSON 特殊处理 json.RawMessage
type RawMessage []byte
当 json.RawMessage 不为 nil 且 len() 为 0 时MarshalJSON 将会解析报错
*/
func MarshalJSON(i interface{}) ([]byte, error) {
m := map[string]interface{}{}
t := reflect.TypeOf(i).Elem()
v := reflect.ValueOf(i).Elem()
fields := reflect_util.GetFields(t)
for _, field := range fields {
key := field.Tag.Get("json")
if key == "" || key == "-" {
continue
}
fieldV := v.FieldByName(field.Name)
value := fieldV.Interface()
switch value.(type) {
case json.RawMessage:
value := value.(json.RawMessage)
if len(value) > 0 {
m[key] = value
}
default:
m[key] = value
}
// MarshalJSON 自定义 json.RawMessage 默认行为
func (m RawMessage) MarshalJSON() ([]byte, error) {
if len(m) == 0 {
return []byte("null"), nil
}
return json.Marshal(m)
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
}