Kev'n Roberts

Object Serializer Utility

Utilities are among my favorites to code. Especially ones that are short and sweet and useful in many different situations. One of my favorites that I wrote was an Object Serializer.

Most examples of object serialization I have seen end up serializing an object to an XML file. That does have it's purpose. However, I've been in many situations where I'd like to serialize an object into XML and use the XML in code. Or I have XML in the form of a string which I need converted to an object.

The XmlSerializer is what we need. And if you look at the Serialize or Deserialize methods, you see that we have a lot of different options. We need some sort of Writer or Reader in order to do the conversion. Since I want to serialize to and deserialize from a string, the obvious choice was the StringWriter (to serialize) and the StringReader (to deserialize).

It is important to note that both the StringWriter and StringReader classes implement IDisposable and the documentation suggests that we should always dispose of our Reader/Writer when we're done with it. I'm a big fan of the "using" statement which automatically calls the Dispose() method when it leaves the using block.

I also decided to use generics so that I could have a strongly typed object going in and coming out.

So without further ado, here it is: 

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
 
namespace KevnRoberts.Utilities
{
    /// <summary>
    /// Used for serializing and deserializing objects
    /// </summary>
    /// <typeparam name="T">The type of object to de/serialize</typeparam>
    public class Serializer<T>
    {
        /// <summary>
        /// Converts the XML into an object
        /// </summary>
        /// <param name="xml">The XML representation of an object.</param>
        /// <returns>An object of type T.</returns>
        public static T Deserialize(string xml)
        {
            // convert to the serializable object
            T item;
 
            using (StringReader reader = new StringReader(xml))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                item = (T)serializer.Deserialize(reader);
            }
 
            return item;
        }
 
        /// <summary>
        /// Converts an object into XML.
        /// </summary>
        /// <param name="obj">The object to convert.</param>
        /// <returns>The XML representation of the object.</returns>
        public static string Serialize(T obj)
        {
            StringBuilder data = new StringBuilder();
 
            using (StringWriter writer = new StringWriter(data))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(writer, obj);
            }
 
            return data.ToString();
        }
    }
}

 

And here is an example of how you would use it:
 

string xml = @"<dateTime>2008-04-03T00:00:00</dateTime>";

DateTime deserializedDate = Serializer<DateTime>.Deserialize(xml);

 

DateTime date = new DateTime(2008, 4, 3);

string serializedDate = Serializer<DateTime>.Serialize(date);

 
Of course, you'll want to use it to de/serialize something more complex than a date and time, but you get the point.

Posted: Apr 03 2008, 12:42 PM by kevnroberts | with 2 comment(s)
Filed under:

Comments

Richard said:

It would probably make more sense to put the generic type parameter on the methods, rather than the class. That way, at least for the serialize method, you don't need to specify the type in the method call:

public static class Serializer

{

   public static T Deserialize<T>(string xml)

   {

       ....

   }

   public static string Serialize<T>(T obj)

   {

       ...

   }

}

DateTime date = new DateTime(2008, 4, 3);

string serializedDate = Serializer.Serialize(date);

# April 4, 2008 11:52 AM

kevnroberts said:

Thanks, Richard.

I didn't know that you could specify a generic type in the method without declaring it in the call to the method. But now I do.

# April 7, 2008 11:48 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)