Thanks to visit codestin.com
Credit goes to github.com

Skip to content

kucukel/SystemTextJsonPatch

 
 

Repository files navigation

SystemTextJsonPatchLogo

CI status Nuget

System Text Json Patch

SystemTextJsonPatch is a JSON Patch (JsonPatchDocument) RFC 6902 implementation for .NET using System.Text.Json

This library tries to ease the migration from Newtonsoft.Json to System.Text.Json by providing similar API for HttpPatch requests as in Microsoft.AspNetCore.JsonPatch and Marvin.JsonPatch

  • Designed as an easy replacement for Microsoft.AspNetCore.JsonPatch
  • Supports .NET 6+ & netstandard2.0

Getting started

Build a patch document on the client. You can use the operations as described in the IETF document: Add, Remove, Replace, Copy, Move and Test.

JsonPatchDocument<DTO.Expense> expensePatch = new JsonPatchDocument<DTO.Expense>();
expensePatch.Replace(e => e.Description, expense.Description);

// serialize it to JSON
var expensePatchJson = System.Text.Json.JsonSerializer.Serialize(expensePatch);

On your API, in the patch method (accept document as parameter & use ApplyTo method)

[Route("api/expenses/{id}")]
[HttpPatch]
public IHttpActionResult Patch(
    int id,
    [FromBody] JsonPatchDocument<DTO.Expense> expensePatchDocument
)
{
      // get the expense from the repository
      var expense = _repository.GetExpense(id);

      // apply the patch document 
      expensePatchDocument.ApplyTo(expense);

      // changes have been applied to expense object
}

Migration from v1

JsonPatchDocumentConverterFactory no longer needs to be set to JsonSerializerOptions. Instead JsonPatchDocument types now use JsonConvertAttribute to use the correct converter.

Performance comparison

This test deserializes a JSON patch document of 8 operations and applies the changes to a new model.

See SystemTextJsonPatch.Benchmark for more details.

BenchmarkDotNet v0.13.7, Windows 11 (10.0.22621.2134/22H2/2022Update/SunValley2) AMD Ryzen 9 5950X, 1 CPU, 32 logical and 16 physical cores .NET SDK 8.0.100-preview.7.23376.3 [Host] : .NET 7.0.9 (7.0.923.32018), X64 RyuJIT AVX2 Job-TMETTY : .NET 7.0.9 (7.0.923.32018), X64 RyuJIT AVX2

WarmupCount=2

Method Mean Error StdDev Gen0 Gen1 Allocated
SystemTextJsonPatch (v3.0.0) 4.953 us 0.0277 us 0.0259 us 0.2899 - 4.83 KB
MarvinJsonPatch (v2.2.1) 909.176 us 17.4292 us 18.6490 us 5.8594 3.9063 96.14 KB
AspNetCoreJsonPatch (v7.0.10) 24.742 us 0.3156 us 0.2952 us 2.6550 0.0610 43.61 KB

About

SystemTextJsonPatch is a JSON Patch (JsonPatchDocument) RFC 6902 implementation for .NET using System.Text.Json

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • C# 99.9%
  • Batchfile 0.1%