So you’ve decided you needed to use inheritance within your object model but are struggling to serialize all the data present on the instances of the types. In a previous post, I wrote about serializing an interface instances using a TypeConverter and you should definitely read that, as this post takes a part from that post. I’ve decided to pull the solution into its own post to make it easier to find for folks.
In this short and simple blog post, you’ll see how to take an array of varying types and serialize all the data, not just the common base class.
The Problem
Say you have a Vehicle base class and want to derive several different vehicles like Car and Bicycle.
And let us say you have these elements declared in a single variable of Vehicle[].
When you go to use System.Text.Json and the JsonSerializer class, you’ll receive the following string JSON output.
As you may have noticed, the serialization process treated each entry in our array as a Vehicle and not the derived type. The result is because the JsonSerializer class looks at the declared type of our parameter to determine the type when we explicitly stated the variable in our code.
The Polymorphic Serialization Solution
To get JsonSerializer to determine the type of each instance correctly, we need to cast our Vehicle[] to an object[]. When the JsonSerializer sees that a parameter type is object, the serializer will call the GetType method on our instances. Here’s the implementation inside of JsonSerializer that performs the type-determination logic.
So, it’s surprisingly easy to get the behavior you want. Cast a collection or type to the object type before calling JsonSerializer.Serialize to get polymorphic serialization.
Running the code above, you’ll see the following results in your console output.
Great! I hope you found this post helpful, and as always, thanks for reading.
Photo by 