Deserialize Inherited class with DataContractSerializer (typeof (BaseClass))

in my Silverlight 4 application, I Serialize / Deserialize data using a DataContractSerializer. I can have two different data types: EditorModel and ConfiguratorModel. Both models inherit from a common base layer.

[DataContract(IsReference = true, Name = "ServiceModel", Namespace = "ServiceModeller.DataModel.Serialization")] [KnownType(typeof(DTO_ServiceModelEditor))] [KnownType(typeof(DTO_ServiceModelConfigurator))] public abstract class DTO_ServiceModelBase { ... } [DataContract(IsReference = true, Name = "ServiceModelEditor", Namespace = "ServiceModeller.DataModel.Serialization")] public class DTO_ServiceModelEditor : DTO_ServiceModelBase { ... } [DataContract(IsReference = true, Name = "ServiceModelConfigurator", Namespace = "ServiceModeller.DataModel.Serialization")] public class DTO_ServiceModelConfigurator : DTO_ServiceModelBase { ... } 

Serialization is not a problem and works as intended. When I deserialize, I don't want to name a specific inherited class, because the user can load EditorModel or ConfiguratorModel. I found https://stackoverflow.com/a/3126148/14829 , answered Mark Gravell, and as far as I understand, I can use the base class when it knows the inherited types (which it does, see KnownType-Declration in DTO_ServiceModelBase).

However, when I do the following Deserialization (I also added both inherited types as a second parameter):

 DataContractSerializer serializer = new DataContractSerializer(typeof(DTO_ServiceModelBase), new Type[] {typeof(DTO_ServiceModelEditor), typeof(DTO_ServiceModelConfigurator)} ); System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.StringReader(stream)); // stream is the serialized string object result; try { result = serializer.ReadObject(reader); } catch (Exception ex) { .. } 

It throws an exception because it expects a "ServiceModel", but has detected a "ServiceModelEditor". Is there something I forgot, or didn’t I answer Mark correctly?

Thanks in advance,
Franc

+6
source share
1 answer

How do you do serialization? When you serialize, you will need to indicate that you are writing objects of the base class DTO_ServiceModelBase, and then it should work. Therefore, when you serialize, simply define a DataContractSerialiser in the same way as in the deserialization example:

 DataContractSerializer serializer = new DataContractSerializer(typeof(DTO_ServiceModelBase), new Type[] {typeof(DTO_ServiceModelEditor), typeof(DTO_ServiceModelConfigurator)} ); 

From the error, it seems that you did something like this:

 DataContractSerializer serializer = new DataContractSerializer(typeof(DTO_ServiceModelEditor)); 
+5
source

Source: https://habr.com/ru/post/902920/


All Articles