Use the latest System.Text.Json features in previous framework versions

System.Text.Json is being rapidly developed and they’re always adding new features that you might want (ex: JsonPropertyOrder in v6). The rapid release cycle makes it difficult to keep your established project on the latest framework version. In fact, trying to keep up would probably be detrimental for your project’s health.

Fortunately, they made a really good decision and made System.Text.Json available as an independent package that’s compatible with previous framework versions. In many cases, this means when you want to use a new feature, you can install the latest System.Text.Json package and don’t need to upgrade your project to the latest framework version.

For example, let’s say your project targets .NET Core 3.1, and you want to use the JsonPropertyOrder feature that was added in v6. You can install the latest System.Text.Json package (note: this is using Views > Other Windows > Package Manager Console):

Install-Package System.Text.Json
Code language: PowerShell (powershell)

This installs the latest System.Text.Json package and enables you to use the latest features:

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Text.Json" Version="6.0.2" /> </ItemGroup> </Project>
Code language: HTML, XML (xml)

Which framework versions does System.Text.Json work with?

At the time of this writing, System.Text.Json v6.0.2 is the current stable version. I tested compatibility against different framework versions. It’s part of .NET 6 and it’s compatible with these previous versions:

  • .NET 5
  • .NET Core 3.1
  • .NET Framework 4.6.1 and above

I also tested System.Text.Json v5.0.0. It’s part of .NET 5 and it’s compatible with these previous versions:

  • .NET Core 2.0 and above
  • .NET Framework 4.6.1 and above

So this means if you’re stuck something on like .NET Core 3.0 and can’t upgrade, you can at least install System.Text.Json v5.0.0.

Quick way to check for compatibility

The System.Text.Json package targets .NET Standard 2.0, but it’s not compatible with all framework versions under .NET Standard 2.0. This leads to the package manager installing the latest version of System.Text.Json even if it’s not truly compatible. When this happens, you’ll get a compiler error like this:

Error System.Runtime.CompilerServices.Unsafe doesn’t support netcoreapp3.0. Consider updating your TargetFramework to netcoreapp3.1 or later

The quickest way to find a compatible version (if any) is to install previous package versions until the compiler errors go away. This is more effective than looking at the package dependency information, since it’s inaccurate. You can use the compatibility info shown in the previous section as a starting point.

Leave a Comment