Browse Source

update jsonutil

marion 4 years ago
parent
commit
87a846b80e
2 changed files with 52 additions and 13 deletions
  1. 29 8
      utils/jsonutil/jsoniter_adapter.go
  2. 23 5
      utils/jsonutil/official_adapter.go

+ 29 - 8
utils/jsonutil/jsoniter_adapter.go

@@ -3,16 +3,37 @@
 package jsonutil
 
 import (
+	"encoding/json"
 	"github.com/json-iterator/go"
 )
 
 var (
-	json                = jsoniter.ConfigCompatibleWithStandardLibrary
-	Marshal             = json.Marshal
-	Unmarshal           = json.Unmarshal
-	MarshalToString     = json.MarshalToString
-	UnmarshalFromString = json.UnmarshalFromString
-	MarshalIndent       = json.MarshalIndent
-	NewDecoder          = json.NewDecoder
-	NewEncoder          = json.NewEncoder
+	adapter = jsoniter.ConfigCompatibleWithStandardLibrary
+	Marshal = func(v interface{}) ([]byte, error) {
+		if nil == v {
+			return nil, nil
+		} else if m, ok := v.(json.Marshaler); ok {
+			return m.MarshalJSON()
+		} else {
+			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 {
+			data, err := m.MarshalJSON()
+			if nil != err {
+				return "", err
+			}
+			return string(data), err
+		} else {
+			return adapter.MarshalToString(v)
+		}
+	}
+	UnmarshalFromString = adapter.UnmarshalFromString
+	MarshalIndent       = adapter.MarshalIndent
+	NewDecoder          = adapter.NewDecoder
+	NewEncoder          = adapter.NewEncoder
 )

+ 23 - 5
utils/jsonutil/official_adapter.go

@@ -8,14 +8,32 @@ import (
 )
 
 var (
-	Marshal         = json.Marshal
+	Marshal = func(v interface{}) ([]byte, error) {
+		if nil == v {
+			return nil, nil
+		} else if m, ok := v.(json.Marshaler); ok {
+			return m.MarshalJSON()
+		} else {
+			return json.Marshal(v)
+		}
+	}
 	Unmarshal       = json.Unmarshal
 	MarshalToString = func(v interface{}) (string, error) {
-		data, err := json.Marshal(v)
-		if nil != err {
-			return "", err
+		if nil == v {
+			return "", nil
+		} else if m, ok := v.(json.Marshaler); ok {
+			data, err := m.MarshalJSON()
+			if nil != err {
+				return "", err
+			}
+			return string(data), err
+		} else {
+			data, err := json.Marshal(v)
+			if nil != err {
+				return "", err
+			}
+			return string(data), nil
 		}
-		return string(data), nil
 	}
 	UnmarshalFromString = func(str string, v interface{}) error {
 		str = strings.TrimSpace(str)