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.)
c # serialization datacontract
Nick Sick Aug 01 '17 at 16:31 on 2017-08-01 16:31
source share