Thus, here's an example of how to serialize any class using it (I'm using UTF8 encoding here, but you can use whatever you like):
public static string SerializeObject<T>(T instance) where T : class
{
try
{
MemoryStream stream = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream, instance);
return new UTF8Encoding().GetString(stream.ToArray());
}
catch(Exception ex)
{
...
}
}
And here's how to deserialize it again:
public static T DeserializeObject<T>(string data) where T : class
{
try
{
MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(data));
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(memoryStream);
}
catch
{
...
}
}
No comments:
Post a Comment