Get JsonPatchDocument operations from an original JSon and an actual JSon

939 views Asked by At

I want to obtain all the operations during comparison of an original json and the actual json. The normal use of JsonPatchDocument is to apply operation on an expandoObject to create a json. I want the reverse, and there is no tool for that. In other word I want to build JsonPatchDocument with all the operation that take the original json to the actual json.

I begin an algo but it will be ugly and not performant.

This piece of the algo will generate only the new property in the json, not the update and the remove.

public static JsonPatchDocument GetAllOperations(string originalJson, string actualJson)
{
    JsonPatchDocument patch = new JsonPatchDocument();

    JObject originalObject = JsonConvert.DeserializeObject<JObject>(originalJson);
    JObject actualObject = JsonConvert.DeserializeObject<JObject>(actualJson);

    foreach (JProperty property in actualObject.Properties())
    {
        if (originalObject[property.Name] == null)
        {
            patch.Add(property.Path, property.Value);
        }
    }
    return patch;
}

Do you any suggest for this kind of algo or an easier way to do it?

0

There are 0 answers