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

本文关键字:之间 对象 json 两个 查找 | 更新日期: 2023-09-27 18:37:17

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

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

using Microsoft.XmlDiffPatch;
using Newtonsoft.Json;

将每个 json 转换为 xml 并使用 MS XmlDiff 库。在 nuget 上可用。差异在另一个xml文档中给出,我在这里写给控制台。例如,这适用于单元测试。

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<JProperty> 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;
}