If you have ever needed to serialize an object in a .NET project then you probably have written serialization code over and over again. It's the kind of code that is very simple, but can be written a hundred ways and is easily forgettable. Also most .NET developers are probably experienced with the XmlSerializer, but don't realize that the DataContractSerializer can do the same things but with much more efficiency and speed. The DataContractSerializer is more performant. So for the benfit of those who haven't already written code to serialize objects, I have created extension methods that attach to all objects and can serialize the object. There is also a method to deserialize any string. Obviously the deserialization is hinged on the fact that the string is a valid data contract. If not, then it won't work, but you knew that... right?
Serializers.zip (258.08 kb)
public static class DataContractSerializationExtensions
{
#region Serialize
public static string Serialize(this T target)
{
return Serialize(target, null);
}
public static string Serialize(this T target, IEnumerable knownTypes)
{
using (var writer = new StringWriter())
{
using (XmlWriter xmlWriter = new XmlTextWriter(writer))
{
var ser = new DataContractSerializer(typeof(T), knownTypes);
ser.WriteObject(xmlWriter, target);
return writer.ToString();
}
}
}
#endregion
#region Deserialize
public static T Deserialize(this string targetString)
{
return Deserialize(targetString, null);
}
public static T Deserialize(this string targetString, IEnumerable knownTypes)
{
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(targetString)))
{
using (var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
{
var ser = new DataContractSerializer(typeof(T), knownTypes);
// Deserialize the data and read it from the instance.
return (T)ser.ReadObject(reader);
}
}
}
#endregion
}
There you go, I have also included the download of the project if you want to run some of the tests I wrote. This is a good start, but notice that I use ASCII encoding. If you use something else, then I suggest you change that. This class could also be changed to work outside of the extension method paradigm. Create a static class and call the methods directly through an API. Have fun with this, and I hope it helps.
Serializers.zip (258.08 kb)