Goodbye custom converters, hello clean polymorphic JSON in .NET 7+#
Ever tried to split lots of different actions into inheritance-friendly classes and interfaces, then make them configurable through a connected frontend?
Sounds easy, right?
 Yeah⊠until you try to serialize and deserialize them with all those different generic parameters floating around. Then things get ugly. đ
The First Attempts (a.k.a. âHow to Make Your Life Harderâ)#
Our first approach was to just use dynamic.
 .NET: âSure, I can do that⊠wait, no, I canât make you a nice mixed list of completely unrelated types without breaking everything.â
Then we tried building custom converters.
They worked, though the approach was both time-consuming and prone to errors.
The Hero Arrives: JsonPolymorphic âš#
Starting from .NET 7, System.Text.Json got a new superpowerâââpolymorphic serialization and deserialization without having to roll your own converter factory from scratch.
Hereâs the magic:
| |
Serializing#
| |
The output now includes a $type discriminator:
| |
Why This Is Awesome đ#
- No more hand-crafted converters (and their inevitable bugs).
- Works out-of-the-box with
System.Text.Json. - Keeps your interfaces intact, so your architecture stays clean.
When deserializing, .NET will look at the $type and automatically pick the right implementation for you.
TL;DR đ#
If youâve been fighting with serializing/deserializing interfaces or abstract classes in .NET and ended up in dynamic hell or converter purgatory,
 âĄïž try JsonPolymorphic and JsonDerivedType.
 Your future self will thank you. đ
