JSON Handling in C#

JSON, Java Script Object Notation, a light weight object representation.
We can convert JSON string to C# object by using the following web site http://json2csharp.com/#

{
"firstName":"John",
"lastName":"Doe",
"dateOfBirth":
	{
		"year":"2000",
		"month":"12",
		"day":"20"
	}
}

This JSON string can be represented by C# class in the following way.

    public class DateOfBirth
    {
        public string year { get; set; }
        public string month { get; set; }
        public string day { get; set; }
    }
    public class RootObject
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public DateOfBirth dateOfBirth { get; set; }
    }

Final code can be shown for Console application in the following way.

using System.Web.Script.Serialization;

namespace Obj_4_4_Serialize_Deserialize_Data
{
    //LISTING 4-79 Using the DataContractJsonSerializer
    public class DateOfBirth
    {
        public string year { get; set; }
        public string month { get; set; }
        public string day { get; set; }
    }
    public class RootObject
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public DateOfBirth dateOfBirth { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("JavaScript Deserialize:");
            string str = @"{""firstName"":""Mahbub"",""lastName"":""Rahman"",""dateOfBirth"":{""year"":""1901"",""month"":""4"",""day"":""30""}}";
            RootObject classForm = new JavaScriptSerializer().Deserialize(str);
            System.Console.WriteLine("FirstName = {0} LastName = {1}", classForm.firstName, classForm.lastName);
            System.Console.WriteLine("Date of Birth = {0}/{1}/{2}", classForm.dateOfBirth.day, classForm.dateOfBirth.month, classForm.dateOfBirth.year);
            System.Console.WriteLine("JavaScript Serialize:");

            RootObject root = new RootObject()
            {
                firstName = "John",
                lastName = "Doe",
                dateOfBirth = new DateOfBirth()
                {
                    day = "20",
                    month = "12",
                    year = "2000"
                }
            };

            string jsonstring = new JavaScriptSerializer().Serialize(root);
            System.Console.WriteLine(jsonstring);

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

is part of Assembly: System.Web.Extensions (in System.Web.Extensions.dll) that need to refer from your project.