Wednesday, December 17, 2008

Generic Serializer-Deserializer

Around one and half year back, I was handling an interesting situation. There were few different systems sending in XML messages, and my component had to accept the message, interpret it and take appropriate actions.

It was easy till I came to know about XML message and its elements and alternate messages. The possibilities were unlimited, and it sounded stupid to hand code/hard code XML elements. Rather than that the solution was designed so that we converted XML -> XSD -> CS. After few changes made here and there to fine tune the CS files with XML, we faced another challenge, we had to serialize/deserialize incoming/outgoing messages. After few minutes of R&D I could pull out this. I've listed the method signature and minor code implementation. It is so simple that you can easily get it working in few minutes.

public static string Serialize<T>(
T data
)
{

//Create the Serializer

XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

//Use the serializer we have just created and serialize the object.

}

the same goes with the Deserializer

public static T Deserialize<T>(
string serializedData
)
{

//check whether the incoming data is not a null string
if (string.IsNullOrEmpty(serializedData))
return default(T); //This can be controversial, so handle with care and as per your requirements, in certain cases you can return null as well, kindly let me know if you have anything that can improvise this code

//create a serializer
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

//Use the deserializer we have just created and deserialize the object.

}

I must thank my friend Sidhartha http://IamJunk.spaces.live.com, as he helped me a lot to enhance the code. I've not published the whole code, in case you need it, drop me an email/comment. I will be more than happy to help you out.

No comments: