3

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?

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
netcoredev
  • 33
  • 1
  • 4
  • so you're using asp.net core for the patch? – Umang Sep 15 '20 at 01:23
  • Thanks for your input. No, in this scenario, it is a Xamarin Forms client that receives a json patch (from an api service) and applies it to a local stored document. – netcoredev Sep 15 '20 at 23:16

1 Answers1

8

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));
    }
}
Umang
  • 815
  • 5
  • 17