Class JsonPatch
Provides functionality for applying a JSON Patch as defined in RFC 6902 to a JSON value.
Inheritance
Inherited Members
Namespace: JsonCons.Utilities
Assembly: JsonCons.Utilities.dll
Syntax
public static class JsonPatch
Examples
The following example borrowed from jsonpatch.com shows how to apply a JSON Patch to a JSON value
using System;
using System.Diagnostics;
using System.Text.Json;
using JsonCons.Utilities;
public class Example
{
public static void Main()
{
using var doc = JsonDocument.Parse(@"
{
""baz"": ""qux"",
""foo"": ""bar""
}
");
using var patch = JsonDocument.Parse(@"
[
{ ""op"": ""replace"", ""path"": ""/baz"", ""value"": ""boo"" },
{ ""op"": ""add"", ""path"": ""/hello"", ""value"": [""world""] },
{ ""op"": ""remove"", ""path"": ""/foo"" }
]
");
using JsonDocument result = JsonPatch.ApplyPatch(doc.RootElement, patch.RootElement);
var options = new JsonSerializerOptions() { WriteIndented = true };
Console.WriteLine("The original document:\n");
Console.WriteLine($"{JsonSerializer.Serialize(doc, options)}\n");
Console.WriteLine("The patch:\n");
Console.WriteLine($"{JsonSerializer.Serialize(patch, options)}\n");
Console.WriteLine("The result:\n");
Console.WriteLine($"{JsonSerializer.Serialize(result, options)}\n");
");
}
}
The original document:
{
"baz": "qux",
"foo": "bar"
}
The patch:
[
{
"op": "replace",
"path": "/baz",
"value": "boo"
},
{
"op": "add",
"path": "/hello",
"value": [
"world"
]
},
{
"op": "remove",
"path": "/foo"
}
]
The result:
{
"baz": "boo",
"hello": [
"world"
]
}
Methods
| Improve this Doc View SourceApplyPatch(JsonElement, JsonElement)
Applies a JSON Patch as defined in RFC 6902 to a source JSON value.
Declaration
public static JsonDocument ApplyPatch(JsonElement source, JsonElement patch)
Parameters
Type | Name | Description |
---|---|---|
System.Text.Json.JsonElement | source | The source JSON value. |
System.Text.Json.JsonElement | patch | The patch to be applied to the source JSON value. |
Returns
Type | Description |
---|---|
System.Text.Json.JsonDocument | The patched JSON value |
Remarks
It is the users responsibilty to properly Dispose the returned System.Text.Json.JsonDocument value
Exceptions
Type | Condition |
---|---|
System.ArgumentException | The provided |
JsonPatchException | A JSON Patch operation failed |
FromDiff(JsonElement, JsonElement)
Builds a JSON Patch as defined in RFC 6902 given two JSON values, a source and a target.
Declaration
public static JsonDocument FromDiff(JsonElement source, JsonElement target)
Parameters
Type | Name | Description |
---|---|---|
System.Text.Json.JsonElement | source | The source JSON value. |
System.Text.Json.JsonElement | target | The target JSON value. |
Returns
Type | Description |
---|---|
System.Text.Json.JsonDocument | A JSON Merge Patch to convert the source JSON value to the target JSON value |
Remarks
It is the users responsibilty to properly Dispose the returned System.Text.Json.JsonDocument value