System.text.json VS Newtonsoft.json

Microsoft shipped a new namespace called System.Text.Json with .NET Core 3.0. This one is integrated with .NET Core 3.0, so you no longer need to install a nuget package.

Why a new JSON serializer?

From what I’ve read I can basically tell you that Microsoft had trouble packaging Newtonsoft inside .NET Core 3.0. So they had to come up with a middle ground which ended up to be system.text.json. There’s also a speed improvement between the new one and the old one. Unfortunately, at a cost of some features that newtonsoft has.

Let’s take a look!

What is the new JSON serializer missing?

So I tried it on an existing code base and ended up with some interesting results:

[DataMember]

It can be a lot of effort to change all your DTO’s to support the new serializer.

Here is the original: https://github.com/dotnet/runtime/issues/30009

If you really want speed, then the new JSON serializer is most definitely not your best option. Utf8Json and JIL have been proved to be 2–4 times faster.

https://michaelscodingspot.com/the-battle-of-c-to-json-serializers-in-net-core-3/

This sample sets ReferenceLoopHandling to Ignore so that looping values are excluded from serialization instead of throwing an exception.

string json = JsonConvert.SerializeObject(foo, Formatting.Indented, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

This is not supported in the new JSON serializer, you’ll end up with exceptions. Although Jozkee made a comment that it should be available in the next version of .NET Core, which will be .NET 5.

Take a look at the comment:

https://github.com/dotnet/runtime/issues/29900#issuecomment-576895618

More information can be found here: https://github.com/dotnet/runtime/issues/29900

The new serializer cannot serialize dynamic types.

dynamic p = JsonSerializer.Parse(json, typeof(ExpandoObject));

Github issue: https://github.com/dotnet/runtime/issues/29690

Conclusion

Let’s do a quick summary:

You want things to work and not worry about missing features?

Newtonsoft is the one to pick here!

Speed is your top priority?

Use something like Utf8Json.

Starting a new project?

I would use System.Text.Json and try to work around the missing features for now. I definitely believe there will be some improvements in the next version of .NET Core. Having the new serializer in your new projects will definitely give you a step ahead when upgrading to .NET 5.

Existing projects?

I advise you to stay on Newtonsoft until the missing features are actually added.

I hope you enjoyed the breakdown between the two.

Happy coding!

--

--

Freelance Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store