Please enable Javascript for better experience...
JSON to C# to JSON-Serialize and Deserialize
By Big | May 4, 2014 | In Articles | Update: Sep 30, 2014 | Total Views [ 6235 ]
(2 Like)
Rate

Now a day whenever we deal in services most of the time data returns either in XML type or in JSON. JSON type is very well prefered by the developers due to its features. But once data comes in either form we need to again convert it into C# object or we can do vice versa also. Here in this article we will see how we can convert JSON object into C# or C# into JSON.

Introduction

Today when everyone running behind services and yes now the world is becoming services oriented JSON is stablishing its own feet around us. It is very much preferable by the developers due to its features. When we get a serialize data which is in the form of JSON, we must deserialize it again in C# object so that it can be resuse in application and data can be fetched from JSON object. We also may need to convert our C# object into JSON to send it over network. Here in this article we will see how we can convert JSON object into C# or C# into JSON.

Model

Let say we have a model created in C#. We will use this model to get/ fetch data. We have name this class as Forecast.cs. We have also created an interface fot this model and named it as IForecast.cs.

The Interface


    /// <summary>
    /// Interface for Forecast
    /// </summary>
    public interface IForecast
    {

        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        /// <value>
        /// The identifier.
        /// </value>
        int Id { get; set; }

        /// <summary>
        /// Gets or sets the date time.
        /// </summary>
        /// <value>
        /// The date time.
        /// </value>
        DateTime CreatedDate { get; set; }

        /// <summary>
        /// Gets or sets the name of the ForeCast.
        /// </summary>
        /// <value>
        /// The name of the ForeCast.
        /// </value>
        string ForeCastName { get; set; }

        /// <summary>
        /// Gets or sets the type of the ForeCast.
        /// </summary>
        /// <value>
        /// The type of the ForeCast.
        /// </value>
        string ForeCastType { get; set; }

        /// <summary>
        /// Gets or sets the depth.
        /// </summary>
        /// <value>
        /// The depth.
        /// </value>
        int Depth { get; set; }

        /// <summary>
        /// Gets or sets the sessions.
        /// </summary>
        /// <value>
        /// The sessions.
        /// </value>
        int Sessions { get; set; }
    }

The Class


    public sealed class Forecast : IForecast
    {
        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        /// <value>
        /// The identifier.
        /// </value>
        public int Id { get; set; }

        /// <summary>
        /// Gets or sets the date time.
        /// </summary>
        /// <value>
        /// The Created Date.
        /// </value>
        public System.DateTime CreatedDate { get; set; }

        /// <summary>
        /// Gets or sets the name of the ForeCast.
        /// </summary>
        /// <value>
        /// The name of the ForeCast.
        /// </value>
        public string ForeCastName { get; set; }

        /// <summary>
        /// Gets or sets the type of the ForeCast.
        /// </summary>
        /// <value>
        /// The type of the ForeCast.
        /// </value>
        public string ForeCastType { get; set; }

        /// <summary>
        /// Gets or sets the depth.
        /// </summary>
        /// <value>
        /// The depth.
        /// </value>
        public int Depth { get; set; }

        /// <summary>
        /// Gets or sets the sessions.
        /// </summary>
        /// <value>
        /// The sessions.
        /// </value>
        public int Sessions { get; set; }
    }

Serialization/Deserialization

Now as we have a model, we can try serialization and deserialization of JSON object into or to C# object. For this we can two methods one for serialize and other to deserialize our JSON object. To achieve this we are using JavaScriptSerializer class. This class can be get in 

DLL-System.Web.Extensions.dll

Namespace:System.Web.Script.Serialization


Let us see the methods to be used for this.Method SerializeObject has been used to serialize C# object into JSON format and the method DeserializeObject has been used to deserialize JSON object into C# object.

Method implementation

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.Script.Serialization;

/// <summary>
/// namespace ForeCastNamespace
/// </summary>
namespace ForeCastNamespace
{
    /// <summary>
    /// ImplementForcast class
    /// </summary>
    public class ImplementForcast
    {
        /// <summary>
        /// Serializes the object.
        /// </summary>
        /// <returns></returns>
        public string SerializeObject()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            var obj = new List<Forecast>();
            obj.Add(new Forecast() { Id = 1, Sessions = 1, CreatedDate = DateTime.Now, Depth = 2, ForeCastName = "Daily", ForeCastType = "Weather Report" });
            obj.Add(new Forecast() { Id = 2, Sessions = 1, CreatedDate = DateTime.Now, Depth = 2, ForeCastName = "wwekly", ForeCastType = "Weather Report" });
            obj.Add(new Forecast() { Id = 3, Sessions = 1, CreatedDate = DateTime.Now, Depth = 2, ForeCastName = "Monthly", ForeCastType = "Weather Report" });


            var serializer = new JavaScriptSerializer();
            var serializedResult = serializer.Serialize(obj);
            return serializedResult;
        }
        /// <summary>
        /// Deserializes the object.
        /// </summary>
        /// <returns></returns>
        public List<Forecast> DeserializeObject()
        {
            var serializer = new JavaScriptSerializer();
            string jsonObject = @"[{""Id"":""1"",""CreatedDate"":""2/3/2014"",""Sessions"":""1"",""Depth"":""1"",""ForeCastName"":""Daily"",""ForeCastType"":""Weather Report""}]";
            var deserializedResult = serializer.Deserialize<List<Forecast>>(jsonObject);
            return deserializedResult;
        }
    }


  public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ImplementForcast obj = new ImplementForcast();
            //To serialze C# object into JSON format use this method
            obj.SerializeObject();
            //To deserialize JSON object into C# object use this method
obj.DeserializeObject();
        }
    }

}

Hope it can help you. Use this code and try yourself.

Share this

About the Author

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment