WCF Generic DataContract object Serializer

The generic DataContract object serializer helps to serialize objects to xml and deserialize the xml to the object.

The generic DataContract object serializer helps to serialize the objects and deserialize the xml to object.

Before reading this article I would recommend you to read the blow article. I am writing this article after reading the below article.

http://www.eggheadcafe.com/tutorials/aspnet/ad947ce6-cd3e-4647-b69c-94d2f3b1b265/datacontractserializer-basics.aspx

The above article explains about the serialization and deserialization of the object. It's very clear and useful information for the WCF developers. In this article I have written a generic Xml serializer class for reusability. You can directly add this class and call SerializeObject and DeserializeXml methods.

Below is the GenericDataContractSerializer class it has two methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

public class GenericDataContractSerializer<T>
    {
        /// <summary>
        /// Serializer
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeObject(T obj)
        {
            try
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                var stringBuilder = new StringBuilder();
                var stringWriter = new StringWriter(stringBuilder);
                xmlSerializer.Serialize(stringWriter, obj);
                return stringBuilder.ToString();
            }
            catch (Exception exception)
            {
                throw new Exception("Failed to serialize data contract object to xml string:", exception);
            }
        }

        /// <summary>
        /// DeserializeXml
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeserializeXml(string xml)
        {
            try
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                return (T)xmlSerializer.Deserialize(new StringReader(xml));
            }
            catch (Exception exception)
            {
                throw new Exception("Failed to deserialize xml string to data contract object:", exception);
             }
        }
     }

To call the methods:

For serialization:
string xmlString = GenericDataContractSerializer<Person>.SerializeObject(person);

For deserialization:
Person dPerson = GenericDataContractSerializer<Person>.DeserializeXml(xmlString);

Below is the code, reused the same Person class from this article(http://www.eggheadcafe.com/tutorials/aspnet/ad947ce6-cd3e-4647-b69c-94d2f3b1b265/datacontractserializer-basics.aspx)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization

[DataContract(Name = "Person", Namespace = "http://www.mypeople.com")]
    public class Person : IExtensibleDataObject
    {
        [DataMember()]
        public string FirstName;
        [DataMember]
        public string LastName;
        [DataMember()]
        public int ID;
        public Person(string newfName, string newLName, int newID)
        {
            FirstName = newfName;
            LastName = newLName;
            ID = newID;
        }
        public Person() { }
        private ExtensionDataObject extensionData_Value;
        // this illustrates using the versioning ExtensionData property, which is not used in the example.
        public ExtensionDataObject ExtensionData
        {
            get
            {
                return extensionData_Value;
            }
            set
            {
                extensionData_Value = value;
            }
        }
    }
To run the code,

  static void Main(string[] args)
   {
            Person person = new Person("Santa", "Clause", 0929);
            string xmlString = GenericDataContractSerializer<Person>.SerializeObject(person);
            Console.WriteLine("Serialized Xml:");
            Console.WriteLine(xmlString);
            Console.WriteLine("========================================================");
            Person dPerson = GenericDataContractSerializer<Person>.DeserializeXml(xmlString);
            Console.WriteLine("Deserialized object data:");
            Console.WriteLine("FirstName:{0}, LastName: {1}, ID: {2}", dPerson.FirstName, dPerson.LastName, dPerson.ID);
            Console.ReadLine();
    }

Below is the output:

Serialized Xml:
<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>Santa</FirstName>
  <LastName>Clause</LastName>
  <ID>929</ID>
</Person>

==============================================
Deserialized object data:
FirstName:Santa, LastName: Clause, ID:929

By Mahesh Sarath   Popularity  (3675 Views)