找出两个json对象之间的差异

.Net中是否有任何库可帮助比较和查找两个json对象之间的差异? 我找到了一些适用于JavaScript的解决方案,但对于C#没什么有趣的。 我的问题的关键是根据比较创建带有以某种方式标记的更改的json。 这样用户就可以看到更改的位置。

using Microsoft.XmlDiffPatch; using Newtonsoft.Json; 

将每个json转换为xml并使用MS XmlDiff库。 可在nuget上使用 。 在另一个xml doc中给出了差异,我在这里写入控制台。 例如,这适用于unit testing。

 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对象,但它将正确应用于您的案例。

 private static string GetJsonDiff(string action, string existing, string modified, string objectType) { // convert JSON to object JObject xptJson = JObject.Parse(modified); JObject actualJson = JObject.Parse(existing); // read properties var xptProps = xptJson.Properties().ToList(); var actProps = actualJson.Properties().ToList(); // find differing properties var auditLog = (from existingProp in actProps from modifiedProp in xptProps where modifiedProp.Path.Equals(existingProp.Path) where !modifiedProp.Value.ToString().Equals(existingProp.Value.ToString()) select new AuditLog { Field = existingProp.Path, OldValue = existingProp.Value.ToString(), NewValue = modifiedProp.Value.ToString(), Action = action, ActionBy = GetUserName(), ActionDate = DateTime.UtcNow.ToLongDateString(), ObjectType = objectType }).ToList(); return JsonConvert.SerializeObject(auditLog); } 

我认为最好的办法是使用JSON.NET创建两个JSON对象,然后递归循环遍历树,比较每个节点,看看它是否存在并且在你去的时候是相等的。

我认为最好的方法是使用newtonsoft json创建对象。 http://www.nuget.org/packages/newtonsoft.json/

因此,您将拥有两个相同类型的对象,您可以轻松地比较和标记差异。

 private IEnumerable JSONCompare(string expectedJSON, string actualJSON) { // convert JSON to object JObject xptJson = JObject.Parse(expectedJSON); JObject actualJson = JObject.Parse(actualJSON); // read properties var xptProps = xptJson.Properties().ToList(); var actProps = actualJson.Properties().ToList(); // find missing properties var missingProps = xptProps.Where(expected => actProps.Where(actual => actual.Name == expected.Name).Count() == 0); return missingProps; }