✅ DataContractSerializer with polymorphisme

Hello everyone. I need help with a topic. I would like to serialize this XML file:

<?xml version="1.0" encoding="utf-8" ?>
<DataBase>
  <Movie Title="Matrix">
    <Duration>110</Duration>
  </Movie>
  <Movie Title="IronMan">
  </Movie>
  <Movie Title="Test">
  </Movie>
</DataBase>


Here's my class that contains my database

[DataContract(Name = "DataBase", Namespace = "")]
public class VideoDataBase
{
    [DataMember] // ????
    public List<Movie> Movies { get; set; }
    
    [OnDeserializing]
    public void OnDeserializing(StreamingContext context)
    {
        Console.WriteLine("Database on Deserializing");
    }
    
    [OnDeserialized]
    public void OnDeserialized(StreamingContext context)
    {
        Console.WriteLine("Database has been deserialized");
    }
    

}


and my generic class

[DataContract]
[KnownType(typeof(Movie))]
public abstract class VideoDatabaseItem
{
    [DataMember]
    public string Title { get; set; }
    
    [OnDeserializing]
    public void OnDeserializing(StreamingContext context)
    {
        Console.WriteLine("VideoDatabaseItem on Deserializing");
    }

}


and finally my Movie Class, which is a derived class of VideoDatabaseItem.

[DataContract]
public class Movie : VideoDatabaseItem
{
    [DataMember(Name = "Duration")]
    public string Duration { get; set; }
    
    [DataMember(Name = "Title")]
    public string Title { get; set; }
    
    [OnDeserializing]
    public new void OnDeserializing(StreamingContext context)
    {
        Console.WriteLine("Movie on Deserializing");
    }
}


I'm having trouble serializing my list with the Movie item, for example. I feel like the inheritance isn't working properly.

I absolutely want to have a generic class for my list of items because later on, I want to be able to serialize other objects.

It would be great if one of you could help me with this topic 🙏🏻
Was this page helpful?