Browse Source

update jsonutil

marion 4 years ago
parent
commit
73329d9a30
1 changed files with 27 additions and 6 deletions
  1. 27 6
      utils/jsonutil/jsoniter_adapter.go

+ 27 - 6
utils/jsonutil/jsoniter_adapter.go

@@ -5,6 +5,7 @@ package jsonutil
 import (
 	"encoding/json"
 	"github.com/json-iterator/go"
+	"reflect"
 )
 
 var (
@@ -12,20 +13,41 @@ var (
 	Marshal = func(v interface{}) ([]byte, error) {
 		if nil == v {
 			return nil, nil
-		} else if m, ok := v.(json.Marshaler); ok {
+		}
+
+		iKind := reflect.TypeOf(v).Kind()
+		ele := reflect.ValueOf(v)
+		if iKind == reflect.Ptr {
+			ele = ele.Elem()
+		}
+		v = ele.Interface()
+		if nil == v {
+			return nil, nil
+		}
+		if m, ok := v.(json.Marshaler); ok {
 			if nil == m {
 				return nil, nil
 			}
 			return m.MarshalJSON()
-		} else {
-			return adapter.Marshal(v)
 		}
+		return adapter.Marshal(v)
 	}
 	Unmarshal       = adapter.Unmarshal
 	MarshalToString = func(v interface{}) (string, error) {
 		if nil == v {
 			return "", nil
-		} else if m, ok := v.(json.Marshaler); ok {
+		}
+
+		iKind := reflect.TypeOf(v).Kind()
+		ele := reflect.ValueOf(v)
+		if iKind == reflect.Ptr {
+			ele = ele.Elem()
+		}
+		v = ele.Interface()
+		if nil == v {
+			return "", nil
+		}
+		if m, ok := v.(json.Marshaler); ok {
 			if nil == m {
 				return "", nil
 			}
@@ -34,9 +56,8 @@ var (
 				return "", err
 			}
 			return string(data), err
-		} else {
-			return adapter.MarshalToString(v)
 		}
+		return adapter.MarshalToString(v)
 	}
 	UnmarshalFromString = adapter.UnmarshalFromString
 	MarshalIndent       = adapter.MarshalIndent