C
C#16mo ago
Boats

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:
var data = Encoding.UTF8.GetBytes(JsonSerializer.Serialize<List<BaseType>>(deriveTypesList));
var data = Encoding.UTF8.GetBytes(JsonSerializer.Serialize<List<BaseType>>(deriveTypesList));
2 Replies
nukleer bomb
nukleer bomb16mo ago
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
Boats
BoatsOP16mo ago
thanks for the docs that clears things up for me
Want results from more Discord servers?
Add your server