Mr Pogan

Mr Pogan

  • NA
  • 3
  • 740

How to deserialize an XML with information about a custom ob

May 5 2016 12:34 AM
I was able to serialize a List of objects (List) using this code:<br /><br />Hide Copy Code<br /><br /><strong>public static string Serialize(object obj)<br />{<br /> &nbsp;&nbsp; using (MemoryStream memoryStream = new MemoryStream())<br /> &nbsp;&nbsp; using (StreamReader reader = new StreamReader(memoryStream))<br /> &nbsp;&nbsp; {<br /> &nbsp;&nbsp; &nbsp;&nbsp; DataContractSerializer serializer = new DataContractSerializer(obj.GetType());<br /> &nbsp;&nbsp; &nbsp;&nbsp; serializer.WriteObject(memoryStream, obj);<br /> &nbsp;&nbsp; &nbsp;&nbsp; memoryStream.Position = 0;<br /> &nbsp;&nbsp; &nbsp;&nbsp; return reader.ReadToEnd();<br /> &nbsp;&nbsp; }<br />}</strong><br /><br /><br />However, I'm not able to deserialize using this code:<br /><br />Hide Copy Code<br /><br /> <strong>public static object Deserialize(string xml, Type toType)<br />{<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; using (Stream stream = new MemoryStream())<br /> &nbsp;&nbsp; &nbsp;&nbsp; {<br /> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; stream.Write(data, 0, data.Length);<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; stream.Position = 0;<br /> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; DataContractSerializer deserializer = new DataContractSerializer(toType);<br /> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; return deserializer.ReadObject(stream);<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />}</strong><br /><br /><br />I'm not able to understand the problem. I'm using the last method by calling it with:<br /><br />Deserialize(SerializedObject, List), but I'm getting an error saying <strong>List is a type, which is not valid in the given context</strong><br /><br />Could anyone help? I'm a bit over my head with this.

Answers (1)