JsonDiffPatch().Diff()对比含邮箱长字符串异常问题排查
问题
我用JsonDiffPatch().Diff()方法对比两个JSON字符串:
var oldJson = {"Author":"admin","Description":"","LastEditedBy":"admin","LastModifiedDate":"8/3/2023 8:53:09 AM","Name":"Export-5","RecipientEmails":"aa@1.com,a@1.com,aaq@1.com,ad@1.com,af@1.com,a@1a.com,a@1v.com,za@1.com,ra@1.com,a@11.co"}; var currentJson = {"Author":"admin","Description":"","LastEditedBy":"admin","LastModifiedDate":"8/3/2023 8:58:14 AM","Name":"Export-5","RecipientEmails":"aa@1.co,a@1.com,aaq@1.com,ad@1.com,af@1.com,a@1a.com,a@1v.com,za@1.com,ra@1.com,a@11.co"} JToken diff = new JsonDiffPatch().Diff(JToken.Parse(oldJson), JToken.Parse(currentJson));
不含邮箱列表时对比结果正常,但包含邮箱列表时,得到的差异如下:
"LastModifiedDate": [ "8/3/2023 8:53:09 AM", "8/3/2023 8:58:14 AM" ] "RecipientEmails": [ "@@ -1,20 +1,19 @@\n aa@1.co\n-m\n ,a@1.com,aaq\n", 0, 2 ]
为什么会出现多余字符?怎么去除这些字符并得到标准的差异数组?完整代码示例:
using System; using JsonDiffPatchDotNet; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class Program { public static void Main() { Console.WriteLine("Hello World"); string oldJson = "{\"RecipientEmails\":\"aa@1.com,a@1.com,aaq@1.com,ad@1.com,af@1.com,a@1a.com,a@1v.com,za@1.com,ra@1.com,a@11.co\"}"; string currentJson = "{\"RecipientEmails\":\"aa@1.co,a@1.com,aaq@1.com,ad@1.com,af@1.com,a@1a.com,a@1v.com,za@1.com,ra@1.com,a@11.co\"}"; JToken diff = new JsonDiffPatch().Diff(JToken.Parse(oldJson), JToken.Parse(currentJson)); Console.WriteLine(diff); } }
原因分析
JsonDiffPatch默认对字符串采用文本差异算法(类似Git的diff格式),当字符串内容较长或被识别为可拆分的文本时,会生成这种带@@标记的diff格式,而非直接返回新旧字符串的数组。这是库默认启用的文本差异优化,目的是针对长字符串只输出变化部分,减少差异结果的体积。
解决方法
要让字符串对比返回标准的新旧值数组,只需修改JsonDiffPatch的配置,关闭文本差异功能,强制对所有字符串使用简单的全量对比。
修改后的代码如下:
using System; using JsonDiffPatchDotNet; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class Program { public static void Main() { Console.WriteLine("Hello World"); string oldJson = "{\"RecipientEmails\":\"aa@1.com,a@1.com,aaq@1.com,ad@1.com,af@1.com,a@1a.com,a@1v.com,za@1.com,ra@1.com,a@11.co\"}"; string currentJson = "{\"RecipientEmails\":\"aa@1.co,a@1.com,aaq@1.com,ad@1.com,af@1.com,a@1a.com,a@1v.com,za@1.com,ra@1.com,a@11.co\"}"; // 配置JsonDiffPatch,禁用文本差异算法 var jdp = new JsonDiffPatch(new JsonDiffPatchOptions { TextDiff = TextDiffMode.Disabled }); JToken diff = jdp.Diff(JToken.Parse(oldJson), JToken.Parse(currentJson)); Console.WriteLine(diff); } }
修改后,RecipientEmails的差异会变成标准的数组格式:
"RecipientEmails": [ "aa@1.com,a@1.com,aaq@1.com,ad@1.com,af@1.com,a@1a.com,a@1v.com,za@1.com,ra@1.com,a@11.co", "aa@1.co,a@1.com,aaq@1.com,ad@1.com,af@1.com,a@1a.com,a@1v.com,za@1.com,ra@1.com,a@11.co" ] --- 内容的提问来源于stack exchange,提问作者tangel
相关产品推荐
相关产品推荐

