问题描述
.Net中是否有任何库可帮助比较和查找两个json对象之间的差异?我找到了一些可用于JavaScript的解决方案,但对C#而言却没有什么有趣的.我的问题的重点是根据比较结果,创建以某种方式标记更改的json.这样用户可以看到更改的位置.
Are there any libraries in .Net to help compare and find differences between two json objects? I've found some solutions available for JavaScript, but nothing interesting for C#. The point of my question is to create json with changes marked in some way, based on the comparison. So that the user could see where the changes are.
推荐答案
using Microsoft.XmlDiffPatch;
using Newtonsoft.Json;
将每个json转换为xml并使用MS XmlDiff库.在 nuget 上可用.差异在另一个xml文档中给出,在这里我写到控制台.例如,这适合于单元测试.
Convert each json to xml and use MS XmlDiff libary. Available on nuget. Differences are given in another xml doc which here I write to the console. This is suitable for unit testing for example.
public bool CompareJson(string expected, string actual)
{
var expectedDoc = JsonConvert.DeserializeXmlNode(expected, "root");
var actualDoc = JsonConvert.DeserializeXmlNode(actual, "root");
var diff = new XmlDiff(XmlDiffOptions.IgnoreWhitespace |
XmlDiffOptions.IgnoreChildOrder);
using (var ms = new MemoryStream())
using (var writer = new XmlTextWriter(ms, Encoding.UTF8))
{
var result = diff.Compare(expectedDoc, actualDoc, writer);
if (!result)
{
ms.Seek(0, SeekOrigin.Begin);
Console.WriteLine(new StreamReader(ms).ReadToEnd());
}
return result;
}
}
这篇关于查找两个json对象之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!