【问题标题】:How can I create a JsonPatchDocument from comparing two c# objects?如何通过比较两个 c# 对象来创建 JsonPatchDocument?
【发布时间】:2023-03-04 23:57:01
【问题描述】:

鉴于我有两个相同类型的 c# 对象,我想比较它们以创建 JsonPatchDocument。

我有一个这样定义的 StyleDetail 类:

public class StyleDetail
    {
        public string Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public decimal OriginalPrice { get; set; }
        public decimal Price { get; set; }
        public string Notes { get; set; }
        public string ImageUrl { get; set; }
        public bool Wishlist { get; set; }
        public List<string> Attributes { get; set; }
        public ColourList Colours { get; set; }
        public SizeList Sizes { get; set; }
        public ResultPage<Style> Related { get; set; }
        public ResultPage<Style> Similar { get; set; }
        public List<Promotion> Promotions { get; set; }
        public int StoreStock { get; set; }
        public StyleDetail()
        {
            Attributes = new List<string>();
            Colours = new ColourList();
            Sizes = new SizeList();
            Promotions = new List<Promotion>();
        }
    }

如果我有两个 StyleDetail 对象

StyleDetail styleNew = db.GetStyle(123);
StyleDetail styleOld = db.GetStyle(456);

我现在想创建一个 JsonPatchDocument,以便将差异发送到我的 REST API... 怎么做??

JsonPatchDocument patch = new JsonPatchDocument();
// Now I want to populate patch with the differences between styleNew and styleOld - how?

在javascript中,有一个库可以做到这一点https://www.npmjs.com/package/rfc6902

计算两个对象之间的差异:

rfc6902.createPatch({first: 'Chris'}, {first: 'Chris', last: '棕色'});

[ { op: 'add', path: '/last', value: 'Brown' } ]

但我正在寻找一个 c# 实现

【问题讨论】:

  • 我知道这有点老了……但你有没有想过如何做到这一点?我正在寻找完全相同的东西!
  • 您可以使用反射来遍历属性并比较它们。有关迭代属性的示例,请参阅此问题:stackoverflow.com/questions/1198886/…

标签: c# json-patch


【解决方案1】:

让我们滥用您的类可序列化为 JSON 的事实! 这是补丁创建者的第一次尝试,它不关心您的实际对象,只关心该对象的 JSON 表示。

public static JsonPatchDocument CreatePatch(object originalObject, object modifiedObject)
{
    var original = JObject.FromObject(originalObject);
    var modified = JObject.FromObject(modifiedObject);

    var patch = new JsonPatchDocument();
    FillPatchForObject(original, modified, patch, "/");

    return patch;
}

static void FillPatchForObject(JObject orig, JObject mod, JsonPatchDocument patch, string path)
{
    var origNames = orig.Properties().Select(x => x.Name).ToArray();
    var modNames = mod.Properties().Select(x => x.Name).ToArray();

    // Names removed in modified
    foreach (var k in origNames.Except(modNames))
    {
        var prop = orig.Property(k);
        patch.Remove(path + prop.Name);
    }

    // Names added in modified
    foreach (var k in modNames.Except(origNames))
    {
        var prop = mod.Property(k);
        patch.Add(path + prop.Name, prop.Value);
    }

    // Present in both
    foreach (var k in origNames.Intersect(modNames))
    {
        var origProp = orig.Property(k);
        var modProp = mod.Property(k);

        if (origProp.Value.Type != modProp.Value.Type)
        {
            patch.Replace(path + modProp.Name, modProp.Value);
        }
        else if (!string.Equals(
                        origProp.Value.ToString(Newtonsoft.Json.Formatting.None),
                        modProp.Value.ToString(Newtonsoft.Json.Formatting.None)))
        {
            if (origProp.Value.Type == JTokenType.Object)
            {
                // Recurse into objects
                FillPatchForObject(origProp.Value as JObject, modProp.Value as JObject, patch, path + modProp.Name +"/");
            }
            else
            {
                // Replace values directly
                patch.Replace(path + modProp.Name, modProp.Value);
            }
        }       
    }
}

用法:

var patch = CreatePatch(
    new { Unchanged = new[] { 1, 2, 3, 4, 5 }, Changed = "1", Removed = "1" },
    new { Unchanged = new[] { 1, 2, 3, 4, 5 }, Changed = "2", Added = new { x = "1" } });

// Result of JsonConvert.SerializeObject(patch)
[
  {
    "path": "/Removed",
    "op": "remove"
  },
  {
    "value": {
      "x": "1"
    },
    "path": "/Added",
    "op": "add"
  },
  {
    "value": "2",
    "path": "/Changed",
    "op": "replace"
  }
]

【讨论】:

  • 顺便说一句 - 您也可以使用完全相同的代码来区分 JSON 字符串,只需从字符串创建 JObject,然后调用 FillPatchForObject
  • 谢谢!大帮助。但是如果我们改变“颜色”,例如在“StyleDetail”类中,它就不能正常工作。
  • 如果直接序列化,“StyleDetail”是否被正确序列化为 JSON?否则我的方法行不通。能否给出 StyleDetail 的定义,以及给出错误的两个示例对象?
  • 这里的区别在于数组。我不会尝试以一种好的方式处理数组,如果有差异,我只是替换整个数组。逐个元素进行比较并不难,但想象一下,如果您有一个包含 700 个元素的数组,并且删除了元素 0。检测这些类型的变化是很复杂的。比较数组的天真方法最终会“替换”元素 0-698,并删除元素 699。
  • 这里是一个更新版本,支持替换数组元素而不是整个数组gist.github.com/yww325/b71563462cb5b5f2ea29e0143634bebe
【解决方案2】:

您可以使用我的 DiffAnalyzer。它基于反射,您可以配置要分析的深度。

https://github.com/rcarubbi/Carubbi.DiffAnalyzer

var before = new User { Id = 1, Name="foo"};
var after= new User  { Id = 2, Name="bar"};
var analyzer = new DiffAnalyzer();
var results = analyzer.Compare(before, after);

【讨论】:

  • 这会返回一个 json 补丁吗?
  • 不,您仍然需要将结果转换为 JsonPatch。不过,您将拥有所有差异。
【解决方案3】:

您可以使用this

您可以使用 NuGet 进行安装,请参阅 NuGet.org 上的 SimpleHelpers.ObjectDiffPatch

PM> Install-Package SimpleHelpers.ObjectDiffPatch

用途:

StyleDetail styleNew = new StyleDetail() { Id = "12", Code = "first" };
StyleDetail styleOld = new StyleDetail() { Id = "23", Code = "second" };
var diff = ObjectDiffPatch.GenerateDiff (styleOld , styleNew );

// original properties values
Console.WriteLine (diff.OldValues.ToString());

// updated properties values
Console.WriteLine (diff.NewValues.ToString());

【讨论】:

  • 这没有回答问题。您是在代码中手动添加要替换的项目,而不是通过比较两个对象来生成补丁文档
  • 对不起,我修好了。
  • 这个项目做了一个 diff,但它没有生成 JsonPatchDocument
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
相关资源
最近更新 更多