Using System.Text.Json to do polymorphic Json conversion in .NET 6

blog header image

DALL-E 2 AI art: Banksy grafiti of a man with a laptop

When using System.Text.Json to serialize complex objects you sometimes need to go a bit beyond how the default serialization works. Here are a few helpful converters - for example for doing polymorphic conversion.

Polymorphic Json Conversion

Often, when I'm serializing complex object in .NET I find myself needing polymorphic serialization. A classic example is this:

I have a List<IMyInterface> property which contain various objects that all have in common that they implement IMyInterface. Normally these doesn't serialize well, cause how would a deserializer know which class to instantiate.

In .NET 7 there is a way to handle this but not in .NET 6 or before. So, inspired by this post I made a generic approach that can easily be added to the Json Converters:

var options = new JsonSerializerOptions();
options.Converters.Add(new PolymorphicJsonConverter<IMyInterface>());

And you should be good to go. The code is in the gist below.



Another useful converter is a simple generic converter that ignores elements of a given type when serializing to Json. 
Sometimes when you serialize large complex types from existing packages you might not want to include everything - and if you are not in control of the types you can't add Ignore attributes to them. But luckily you can just ignore them as part of the serialization. See the converter below and attach it in the same way as above.



The last useful converter snippet I will share here is this one. There might be times when you want to decide yourself how a given type is serialized to a string - and this will help you do it.

Assume for example that you have a very large object inside another serialized object, but all you really want to serialize is the ID property of it - then you can simply use it like this:

options.Converters.Add(newCustomStringConversionJsonConverter<MyVeryDetailedType>(mvdt => mvdt.ID.ToString(), s => new MyVeryDetailsType(){ID = Int.Parse(s)});


I hope you find the above useful. Remember to leave a comment if you have any suggestions!


Recent posts