Serialize/Deserialize .NET objects to XML and JSON format

Here I am describing on serializing and deserializing the .NET objects to XML and JSON formats using C#.NET.

For this, first I have constructed a class object with few properties. Here is the class I have created to serialize it to XML and JSON formats:
[System.Xml.Serialization.XmlRoot]
    public class sriClass
    {
        [System.Xml.Serialization.XmlAttribute]
        public int ID
        { set; get; }
        
        public string Name
        { set; get; }
        
        public string Country
        { set; get; }
        
        public string Address1
        { set; get; }
        
        public string Address2
        { set; get; }

        [System.Xml.Serialization.XmlIgnore]
        public string Address3
        { set; get; }
        
        public string Profile1
        { set; get; }
        
        public string Profile2
        { set; get; }

        [System.Xml.Serialization.XmlIgnore]
        public string Profile3
        { set; get; }
    }
The above class sriClass name is declared as XmlRoot, means sriClass is the root element on serializing into XML format. And the property ID will act as attribute for the root node; Address3 and Profile3 properties were ignored by the XML document on serialization.

Before serializing the class into any of the format, instantiate the class and its properties:
            sriClass sr = new sriClass();
            sr.ID = 1234;
            sr.Name = "srinu";
            sr.Country = "India";
            sr.Address1 = "Addr1";
            sr.Address2 = "Addr2";
            sr.Address3 = "Addr3";
            sr.Profile1 = "Profile1";
            sr.Profile2 = "Profile2";
            sr.Profile3 = "Profile3";
Serialize/Deserialize into XML format:

In .NET XmlSerializer class can be used to serialize the object into XML format and deserialize the XML string into object format. Below is the sample code to serialize and deserialize the above class object:
   MemoryStream ms = new MemoryStream();
            System.Xml.Serialization.XmlSerializer xs = new XmlSerializer(typeof(sriClass));
            xs.Serialize(ms, sr);
            ms.Position = 0;

            StreamReader reader = new StreamReader(ms);
            string xml = reader.ReadToEnd();
            ms.Position = 0;

            sriClass srXml = (sriClass)xs.Deserialize(ms);
Serialize/Deserialize into JSON format:

JavaScriptSerializer class would be helped out in .NET to serialize the object into JSON format and deserialize the JSON string into object format. Below is the sample code for this object conversions:
   JavaScriptSerializer jss = new JavaScriptSerializer();
            string strSr = jss.Serialize(sr);

            sriClass srJson1 = (sriClass)jss.Deserialize(strSr, typeof(sriClass)); [OR]
            sriClass srJson2 = jss.Deserialize<sriClass>(strSr);

No comments:

Powered by Blogger.