Cant deserilize derived class. But it works if it is included in a list or dictionary. Any suggestions?

I had a strange problem when I can serialize a derived class if I put it on a list, but not when it stands on it.

I use these methods for serialization and deserialization (found them here ):

public static string Serialize(T obj) { using (MemoryStream memoryStream = new MemoryStream()) using (StreamReader reader = new StreamReader(memoryStream)) { DataContractSerializer serializer = new DataContractSerializer(obj.GetType()); serializer.WriteObject(memoryStream, obj); memoryStream.Position = 0; return reader.ReadToEnd(); } } public static T Deserialize(string xml, Type toType) { using (Stream stream = new MemoryStream()) { byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); stream.Write(data, 0, data.Length); stream.Position = 0; DataContractSerializer deserializer = new DataContractSerializer(toType); return (T)deserializer.ReadObject(stream); } } 

I have an Entity base class. And a derived class of Thing .

 [DataContract] [KnownType(typeof(Thing))] Class Entity { } [DataContract] Class Thing : Entity { } 

Now, when I try to serialize an object created as Thing , there is no problem, but deserialization gives an error.

  Thing e = new Thing(); string xmlstring = XML<Entity>.Serialize(e); Entity testE = XML<Entity>.Deserialize(xmlstring, typeof(Entity)); 

The error says something like Expected element Entity from ... . Element Thing was found. Expected element Entity from ... . Element Thing was found. (was not written in English.)

But it’s strange that it works if I put an object in a list and serialize-deserialize the list.

  Thing e = new Thing(); List<Entity> test = new List<Entity>(); test.Add(e); var xmlstring = XML<List<Entity>>.Serialize(test); List<Entity> test2 = XML<List<Entity>>.Deserialize(xmlstring, typeof(List<Entity>)); 

Now test2 has an entry with the correct Thing character. Even if this can be a workaround, it certainly should be a simpler way, and it should be something that would be easy to fix, I think? Any suggestions? What did I miss?

(And, of course, this works when deserializing my Thing object as a Thing object, but this is not what I want, when deserializing I will not know the class in advance.)

0
c # serialization datacontract
Aug 01 '17 at 16:31 on
source share
1 answer

I seem to have found a workaround after thinking about Jaya 's @ comments . I modified the serialize method to make it serialize to a base class type. Initially, I did not think it would work, but it was!

 public static string Serialize(T obj, Type toType) { using (MemoryStream memoryStream = new MemoryStream()) using (StreamReader reader = new StreamReader(memoryStream)) { DataContractSerializer serializer = new DataContractSerializer(toType); serializer.WriteObject(memoryStream, obj); memoryStream.Position = 0; return reader.ReadToEnd(); } } 
0
Aug 01 '17 at 17:07 on
source share



All Articles