Created
October 30, 2013 15:39
-
-
Save feanz/7234775 to your computer and use it in GitHub Desktop.
SerializationExtensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class SerializationExtensions | |
{ | |
public static string Serialize(this object obj) | |
{ | |
using (var memoryStream = new MemoryStream()) | |
using (var reader = new StreamReader(memoryStream)) | |
{ | |
var serializer = new DataContractSerializer(obj.GetType()); | |
serializer.WriteObject(memoryStream, obj); | |
memoryStream.Position = 0; | |
return reader.ReadToEnd(); | |
} | |
} | |
public static object Deserialize(this string text, Type toType) | |
{ | |
using (Stream stream = new MemoryStream()) | |
{ | |
var data = System.Text.Encoding.UTF8.GetBytes(text); | |
stream.Write(data, 0, data.Length); | |
stream.Position = 0; | |
var deserializer = new DataContractSerializer(toType); | |
return deserializer.ReadObject(stream); | |
} | |
} | |
public static T Deserialize<T>(this string text) | |
{ | |
var result = text.Deserialize(typeof(T)); | |
if (result != null) | |
{ | |
return (T)result; | |
} | |
return default(T); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment