浏览代码

JsonSerializerOptions 使用 Encoder 解决非ASCII文字转义

Roc 5 年之前
父节点
当前提交
0b698727ca

+ 4 - 2
src/Essensoft.AspNetCore.Payment.Alipay/AlipayClient.cs

@@ -2,7 +2,9 @@
 using System.Collections.Generic;
 using System.Net.Http;
 using System.Text;
+using System.Text.Encodings.Web;
 using System.Text.Json;
+using System.Text.Unicode;
 using System.Threading.Tasks;
 using Essensoft.AspNetCore.Payment.Alipay.Parser;
 using Essensoft.AspNetCore.Payment.Alipay.Request;
@@ -648,7 +650,7 @@ namespace Essensoft.AspNetCore.Payment.Alipay
 
         #region Model Serialize
 
-        private static readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions { IgnoreNullValues = true };
+        private static readonly JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions { IgnoreNullValues = true , Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) };
 
         private AlipayDictionary SerializeBizModel<T>(AlipayDictionary requestParams, IAlipayRequest<T> request) where T : AlipayResponse
         {
@@ -657,7 +659,7 @@ namespace Essensoft.AspNetCore.Payment.Alipay
             var bizModel = request.GetBizModel();
             if (isBizContentEmpty && bizModel != null)
             {
-                var content = JsonSerializer.Serialize(bizModel, bizModel.GetType(), _jsonSerializerOptions);
+                var content = JsonSerializer.Serialize(bizModel, bizModel.GetType(), jsonSerializerOptions);
                 result.Add(AlipayConstants.BIZ_CONTENT, content);
             }
 

+ 6 - 2
src/Essensoft.AspNetCore.Payment.Alipay/Parser/AlipayDictionaryParser.cs

@@ -1,11 +1,15 @@
 using System;
 using System.Collections.Generic;
+using System.Text.Encodings.Web;
 using System.Text.Json;
+using System.Text.Unicode;
 
 namespace Essensoft.AspNetCore.Payment.Alipay.Parser
 {
     public static class AlipayDictionaryParser
     {
+        private static readonly JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions { IgnoreNullValues = true, Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) };
+
         public static T Parse<T>(IDictionary<string, string> dictionary) where T : AlipayObject
         {
             if (dictionary == null || dictionary.Count == 0)
@@ -17,8 +21,8 @@ namespace Essensoft.AspNetCore.Payment.Alipay.Parser
 
             try
             {
-                var jsonText = JsonSerializer.Serialize(dictionary);
-                result = JsonSerializer.Deserialize<T>(jsonText);
+                var jsonText = JsonSerializer.Serialize(dictionary, jsonSerializerOptions);
+                result = JsonSerializer.Deserialize<T>(jsonText, jsonSerializerOptions);
             }
             catch { }