in my Silverlight 4 application, I Serialize/Deserialize data with DataContractSerializer. I can have two different types of data: The EditorModel and the ConfiguratorModel. Both models inherit from a common baseclass.
[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 { ... }
Serializing is no problem and works as intended. When I deserialize, I do not want to name the specific inherited class, because the user can load EditorModel or ConfiguratorModel as well. I found this stackoverflowquestion, answered by Marc Gravell, and as I understand it, I can use the base class when it knows the inherited types (which it does, see the KnownType-Declaration at DTO_ServiceModelBase).
Still, when I do the following Deserialization (I also added both inherited types as the 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 "ServiceModel" but found "ServiceModelEditor". Is there anything I forgot, or did I got Marc's answer wrong?
Thanks in advance,
Frank