Last active
July 26, 2019 18:53
-
-
Save mtzaldo/1175ab50a8d5ae66fdc184ba7d39863f to your computer and use it in GitHub Desktop.
Convert a plain object to JsonPatchDocument<T> (including Dictionary)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Marvin.JsonPatch; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
using Newtonsoft.Json.Linq; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Marvin.JsonPatch.Operations; | |
namespace MyProject.ModelsExtensions | |
{ | |
public static class JsonPatchDocumentExtension | |
{ | |
public static JsonPatchDocument<T> From<T>(T t) where T : class | |
{ | |
var json = JObject.FromObject(t, | |
new JsonSerializer() { | |
ContractResolver = new CamelCasePropertyNamesContractResolver(), | |
NullValueHandling = NullValueHandling.Ignore | |
}); | |
var objProps = json.Properties().Select(p => p as JProperty); | |
var properties = new Stack<JProperty>(objProps); | |
var operations = new List<Operation<T>>(); | |
JProperty prop = null; | |
JObject obj = null; | |
JArray arr = null; | |
while(properties.Count > 0) | |
{ | |
prop = properties.Pop(); | |
if (prop.Value is JObject) | |
{ | |
obj = prop.Value as JObject; | |
objProps = obj.Properties().Select(p => p as JProperty); | |
foreach(var o in objProps) | |
{ | |
properties.Push(o); | |
} | |
} | |
else if(prop.Value is JArray) | |
{ | |
arr = prop.Value as JArray; | |
obj = arr.First as JObject; | |
do | |
{ | |
objProps = obj.Properties().Select(p => p as JProperty); | |
foreach (var o in objProps) | |
{ | |
properties.Push(o); | |
} | |
obj = obj.Next as JObject; | |
} while (obj != null); | |
} | |
else | |
{ | |
operations.Add( | |
new Operation<T>() | |
{ | |
path = $"/{prop.Path.Replace(".", "/")}", | |
value = prop.Value, | |
op = "replace" | |
}); | |
} | |
} | |
return new JsonPatchDocument<T>(operations); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You save my life. Thanks !