Skip to content

Easy JSON deserialization with the new .NET built-in libraries

Old school .NET developers are very well used to Newtonsoft.Json, as this has always been the go-to library aimed at serializing and deserializing JSON objects during times where the .NET framework didn’t offer any good support for it.

Not long ago tho, and starting with .NET Core 3, the team behind .NET introduced the new namespace — System.Text.Json — containing a set of cool built-in features to deal with JSON serialization and deserialization.

And even more recently, we were introduced to System.Net.Http.Json.

This namespace builds on top of System.Text.Json and fully integrates with HttpClients via extension methods in order to enable easier JSON serialization and deserialization during HTTP calls involving rest APIs.

Let’s take a look and what has changed by using as an example a simple HTTP GET operation that retrieves some JSON information from the network and deserializes it into a MyObject instance:

Here’s a snippet of how we used to do things using the old Newtonsoft classes:

Overall, this piece of code works just fine but also brings in a certain degree of complexity involving some HTTP-related statements, a few low-level stream operations, and finally the deserialization of the content of our GET operation.

All that complexity often led devs to implement a shorter but less optimal deserialization routine:

And while that also works fine, it is known that creating intermediary strings for the sole purpose of creating another object and throwing the initial string away is a total waste of memory and can often lead to more application pauses due to a higher number of GC-cycles being needed to clean that memory.

That is especially true for large JSON objects.

The new System.Net.Http.Json namespace provides us with some alternative methods for serializing and deserializing JSON. Here’s a snippet of how we can deserialize our HTTP content using the ReadFromJsonAsync extension method: 

It’s also possible to skip the check for status code and opt for a null-check instead by using the GetFromJsonAsync extension method:

The above options provide the perfect blend between simplicity and efficiency since all the complexity of dealing with the underlying streams and properly deserializing JSON objects is abstracted away from and built-in internally into the framework.

And if you are really into one-liners, our last code-snippet can still be reduced further to something like: 

Two other fun methods to try out are PostAsJsonAsync and PutAsJsonAsync. Both work very similarly and according to their respective HTTP methods.

Leave a Reply

Your email address will not be published.