Using DataContractSerializer to serialize, but can't deserialize back
Solution 1:
Here is how I've always done it:
public static string Serialize(object 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 object 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 deserializer.ReadObject(stream);
}
}
Solution 2:
Other solution is:
public static T Deserialize<T>(string rawXml)
{
using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
{
DataContractSerializer formatter0 =
new DataContractSerializer(typeof(T));
return (T)formatter0.ReadObject(reader);
}
}
One remark: sometimes it happens that raw xml contains e.g.:
<?xml version="1.0" encoding="utf-16"?>
then of course you can't use UTF8 encoding used in other examples..