mirror of
https://github.com/alireza0/x-ui.git
synced 2026-03-13 21:13:09 +00:00
0.0.1
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user