json.go 769 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package json_util
  2. import (
  3. "encoding/json"
  4. "reflect"
  5. "x-ui/util/reflect_util"
  6. )
  7. /*
  8. MarshalJSON 特殊处理 json.RawMessage
  9. 当 json.RawMessage 不为 nil 且 len() 为 0 时,MarshalJSON 将会解析报错
  10. */
  11. func MarshalJSON(i interface{}) ([]byte, error) {
  12. m := map[string]interface{}{}
  13. t := reflect.TypeOf(i).Elem()
  14. v := reflect.ValueOf(i).Elem()
  15. fields := reflect_util.GetFields(t)
  16. for _, field := range fields {
  17. key := field.Tag.Get("json")
  18. if key == "" || key == "-" {
  19. continue
  20. }
  21. fieldV := v.FieldByName(field.Name)
  22. value := fieldV.Interface()
  23. switch value.(type) {
  24. case json.RawMessage:
  25. value := value.(json.RawMessage)
  26. if len(value) > 0 {
  27. m[key] = value
  28. }
  29. default:
  30. m[key] = value
  31. }
  32. }
  33. return json.Marshal(m)
  34. }