Serializing a derived class with System.Text.Json
Hello I'm currently running into the following error: "Cannot convert List<DerivedType> to List<BaseType> when trying to use System.Text.Json to serialize a derive class.
DerivedType has a bunch of properties that I am not interested in serializing, The BaseType has properties such as Name, StartTime, and Endtime that I am interested in storing. Is there a way to get this to work. The only thing i can get working is to loop through the list of derive types and just convert them to the base type and passing that list through to the serialize.
I've added a snippet below:
2 Replies
You are getting this error not because of JSON serialization, but because covariance and contravariance https://learn.microsoft.com/dotnet/standard/generics/covariance-and-contravariance
About polymorphic serialization, https://learn.microsoft.com/dotnet/standard/serialization/system-text-json/polymorphism
thanks for the docs that clears things up for me