Practical Approach of Converting JSON String to Object and ViceVesra using JavascriptSerializer c#

Advantage of using it:

  1. Convert JSON string to Object.
  2. Convert Object to JSON String.
  3. It is used in AJAX.
  4. Provide help to web service to work with client application.
  5. Helps to connect the web Service with JavaScript.

Steps to be followed to Serialize and DeSerialze JSON String:

Step 1: Used Namespace:

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

Step 2: Used Class for Demo:

   
[Serializable]
    public class College
    {
        public string CollegeName;
        public int CollegeRank;
    } 
    [Serializable]
    public class Student
    {
        public College CollegeInfo;
        public string Name;
        public int Rank;
    }

Step 3: Example JSON String:

    string example = "{\"CollegeInfo\":{\"CollegeName\":\"VelTech\",\"CollegeRank\":\"10\"}," +
                             "\"Name\":\"Lajapathy\",\"Rank\":\"50\"}";


Step 4: Creating Instance of JavaScriptSerializer

   
JavaScriptSerializer serializer = new JavaScriptSerializer();

Step 5: DeSerializing the JSON String

    // Deserialize
    Student student = serializer.Deserialize<Student>(example);

Step 6: Displaying the DeSerialized String by adding to String Builder and shown in Label

    //Adding College info into the StringBuilder and assigned to Label.
    StringBuilder sb = new StringBuilder();
    sb.Append("CollegeInfo = (" + student.CollegeInfo.CollegeName + ", " +
    student.CollegeInfo.CollegeRank + ")" + "<br/>");
 
    sb.Append("Name = " + student.Name);
    litDeserialization.Text = sb.ToString();

Step 7: Serializing Student Object back to JSON String.

    // Serialize
    string jsonString = serializer.Serialize(student);

Step 8: Displaying the Serialized string in Lable

    //Assigning JSON string to Label.
    litSerialization.Text = jsonString;

Step 9: Output for Deserializing the JSON String

json.gif

Step 10: Output for serializing the Student Object

json1.gif

Download the Source code and edit the class and check the output, so it helps to make you understand clearly, how the class converts to JSON string.

Thanks for reading this blog. If you like this article, just leave a comment.