Let me misuse the fact that your classes are serializable in JSON! Here is the first attempt by the patch creator, who does not care about your real object, only about the JSON representation of this object.
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();
Using:
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" } ]
source share