How to apply json-patch to plain json in .net core?

Viewed 2370

JsonPatchDocument.Apply method works on an object graph, but instead I want to apply a json patch to plain json.

For example, suppose I have this json:

{ "name": "JSON Patch", "text": "OLD" } 

How can I apply a patch like this with C#?

[ { "op": "replace", "path": "/text", "value": "NEW VALUE" } ] 

How is this done using C# and .NET core?

1 Answers

Here is a snippet of code which applies patch:

using System;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        var json="{ \"name\": \"JSON Patch\", \"text\": \"OLD\" }";
        var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
        var operationStrings = "[ { \"op\": \"replace\", \"path\": \"/text\", \"value\": \"NEW VALUE\" } ] ";
        var ops = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Microsoft.AspNetCore.JsonPatch.Operations.Operation>>(operationStrings);
        
        var patchDocument = new Microsoft.AspNetCore.JsonPatch.JsonPatchDocument(ops, new Newtonsoft.Json.Serialization.DefaultContractResolver());
        
        patchDocument.ApplyTo(jsonObj);
        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj));
    }
}
Related