How to merge JSON documents in .NET Core and .NET 5?
Let’s say we have two JSON documents that we would like to merge. How can this be achieved?
Using Newtonsoft.Json
In .NET Core, until version 3 was released, the default serializer was the well-known and liked Newtonsoft.Json
. Merging JSON documents with this library is very simple:
var object_A = JObject.Parse("{ 'A': 1, 'B': 2, 'C': 3 }");
var object_B = JObject.Parse("{ 'C': 4, 'D': 5, 'E': 6 }");
var object_C = new JObject();
object_C.Merge(object_A);
object_C.Merge(object_B);
/*
object_C is:
{
"A": 1,
"B": 2,
"C": 4,
"D": 5,
"E": 6
}
*/
Here comes System.Text.Json
System.Text.Json
was released with the release of .NET Core 3, and it is part of its runtime. However, it can be used with earlier versions of .NET Core by installing the appropriate NuGet package.
So, how to merge JSON documents with a brand new, blazing fast library released by Microsoft? It turns out that at the time of writing this post, there is no user-friendly API implemented yet.
Does that mean it is impossible? Definitely not. While looking for a way to solve this problem, I came across an article on the Microsoft website that described the differences between System.Text.Json
and Newtonsoft.Json
.
For performance reasons, the JsonDocument
object is read-only as opposed to the JObject
. This is the reason why Microsoft has not implemented the document merge API. Fortunately, there is an API suggestion that is covered in this GitHub issue. It seems that the proposed API is faster than the API of the Newtonsoft.Json
library.
Here is a BenchmarkDotNet comparison results of both APIs:
Method | Mean | Error | StdDev | Median | Min | Max | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated |
---|---|---|---|---|---|---|---|---|---|---|---|
MergeNewtonsoft | 29.01 us | 0.570 us | 0.656 us | 28.84 us | 28.13 us | 30.19 us | 1.00 | 7.0801 | 0.0610 | - | 28.98 KB |
Merge_New | 16.41 us | 0.293 us | 0.274 us | 16.41 us | 16.02 us | 17.00 us | 0.57 | 1.7090 | - | - | 6.99 KB |
Final thoughts
It looks like System.Text.Json
will stay with us longer. I wonder if it will get an official API implementation for merging JSON documents. What do you think? If you have any interesting thoughts on this topic please let me know!