Serialization is used everywhere in programming modern apps for data sent via web-based API’s, used in ASP.NET view models and even for databases like Cosmos DB since its internal storage is JSON. I even serialize configuration objects to and from disk for apps that I write to store app and user data.
I would say JSON this the most popular way to do serialization due to it being less verbose than XML and therefore can be more performant. Before .NET Core and even before NuGet, the most widely used library to serialize JSON is Newtonsoft.Json with over 266 million downloads to date!
It’s so popular that even Microsoft uses it, even though .NET and .NET Core (even before version 3) can serialize JSON (via the DataContractJsonSerializer). This free library has a lot of features and is easy to use.
For the remainder of this article, I will show how to use it and show performance data from the second edition (also released today) of my book Rock Your Code: Code & App Performance for Microsoft .NET.
Serializing an Object to JSON
For the examples I will show, I will be serializing a collection of a real-world object called Person from my NuGet package that I use for benchmarking and testing code. I have already written in detail about the proper way of serializing objects in this article.
Serializing objects to JSON using the Newtonsoft library is as easy as one line of code:
var json = JsonConvert.SerializeObject(people);
Using the new JSON serializer in .NET Core 3 is also one line of code:
var json = JsonSerializer.Serialize(people);
Let’s look at my benchmark tests done at different collection sizes.
The tests show that using JsonConvert is slightly faster than using the new JsonSerializer. Really too close to pick a clear winner for performance.
Deserializing JSON to an Object
Again, deserializing JSON back to an object is as simple as one line of code. Using the Newtonsoft library looks like this:
var people = JsonConvert.DeserializeObject<List<Person>>(json);
Using the new JsonSerializer looks like this:
var people = JsonSerializer.Deserialize(json, typeof(List<Person>)) as List<Person>;
I wished that the JsonSerializer used the same simpler syntax that JsonConvert does. Let’s look at the performance results.
As you can see, using the new JsonSerializer is the clear winner on performance when deserializing JSON!
The benchmark results show that using the new JsonSerializer in .NET Core 3 is overall more performant. I hope that this article will encourage you to look at it. The only drawback is that the JsonSerializer is not part of .NET Standard 2.1. Which means if you have libraries written in .NET Standard 2.1 (like I do), you will need to use the DataContractJsonSerializer or the Netwonsoft library. I recommend benchmarking your own types to ensure you are getting the best performance for your app.
I plan to write more articles about the new JsonSerializer in future articles. Do you have any comments or questions? Please make a comment below.