Tuesday, February 16, 2010

Simple Serializer for C#

Nothing too special here, just a utility class to help serialize objects quickly and easily.


public static class Serializer
{
    /// <summary>
    /// Serialize the given object into UTF-8 encoded XML
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public static string Serialize(object item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }

        using (var stream = new MemoryStream())
        {
            // This constructor is automatically cached, so no need for the
            // local cache.
            var serializer = new XmlSerializer(item.GetType());

            serializer.Serialize(stream, item);
            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }

    /// <summary>
    /// Deserialize the given UTF-8 encoded XML string
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="xml"></param>
    /// <returns></returns>
    public static T Deserialize<T>(string xml)
    {
        using (var stream = new MemoryStream(xml.ToByteArray()))
        {
            // This constructor is automatically cached, so no need for the
            // local cache.
            var serializer = new XmlSerializer(typeof(T));

            return (T)serializer.Deserialize(stream);
        }
    }
}

Usage is pretty simple:

MyClass instance = new MyClass();
Serializer.Write<MyClass>(instance, "instance.xml");

MyClass instance_2 = Serializer.Read<MyClass>("instance.xml");

Edit, 1/30/13


When targeting heirarchies and inherited types, the XML serializer can leak memory. Basically, when you create a new serializer, it will create an assembly at runtime. The basic constructors of XmlSerializer will cache this assembly automatically on their own, but when working with an inherited type (this constructor), it won't be. So, here's an expanded helper that works with inherited types and caches XmlSerializers.


Updated Xml Helper

No comments:

Post a Comment