Different ways of doing serialization and deserialization in .Net (Asp.net/Asp.net MVC)(Part 2)


different-ways-of-doing-serialization-and-deserialization-in-net-asp-netasp-net-mvc (Part 1)

Method 2 approach

we will use System.Web.Script.Serialization namespace of .net framework

Step 1: Create the EmpDemo Class and write the code in code behind file like given below


using System;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    public partial class Demo1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            EmpDemo objEmp = new EmpDemo
            {
                Id = 1021,
                EmpName = "Chandradev",
                EmpAddress = "Bangalore"
            };

            JavaScriptSerializer js = new JavaScriptSerializer();

            Response.Write("<b>Converting to Json </b> " + "</br>");
            Response.Write("</br>");
            string jsonData = js.Serialize(objEmp);
            Response.Write(jsonData);
            Response.Write("</br>");

            var objEmp1 = js.Deserialize(jsonData);
            Response.Write("</br>");
            Response.Write("<b> Converting Json to .Net Object: </b>");
            Response.Write("</br>");
            Response.Write("Id: " + objEmp1.Id + "</br>");
            Response.Write("EmpName: " + objEmp1.EmpName + "</br>");
            Response.Write("EmpAddress: " + objEmp1.EmpAddress + "</br>");
        }
    }

    public class EmpDemo
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
    }
}

Summary: This approach will be suitable in asp.net or asp.net mvc application.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: