C# – Using JavaScriptSerializer to convert objects to JSON

I was working with Ajax and came across a situation where server response was required in JSON format. OK there are ways to manually create such a response but the code will look crap, coupled and re-usability of the code will hurt!!!! So a better solution would be required to handle such situation.

Luckily C# provides a way to convert an object to JSON. Here, I will take you through a simple example consisting of following steps:

  1. Creating a Person class
  2. Initializing one or more objects of Person class
  3. Creating a List of all Person objects
  4. Converting List to JSON
The solution is applicable for .NET 3.5 or above.  If you want to use this functionality with .NET version prior to 3.5 then you will have to add reference to  System.Web.Extentions dll library. 
public class Student 
{       
  public string FirstName { get; set; }       
  public string LastName { get; set; }
  public string Age { get; set; }
  public string ID { get; set; }
}

Let’s add few instances:

Student student01 = new Student { FirstName = "Ali", LastName="Raza", ID = "000001", Age = "24" };
Student student02 = new Student { FirstName = "Shahazad", LastName = "Ahmed", ID = "000002", Age = "26" };
Student student03 = new Student { FirstName = "Arslan", LastName = "Ahmer", ID = "000003", Age = "27" };
And finally serialization:
List<Student> studentList = new List<Student>() { student01, student02, student03 };
System.Web.Script.Serialization.JavaScriptSerializer jsSerializer =
     new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsSerializer.Serialize(studentList);
The output you get through json string object is:
[{ "FirstName" = "Ali", "LastName" = "Raza", "ID" = "000001", "Age" = "24" },
{ "FirstName" = "Shahazad", "LastName" = "Ahmed", "ID" = "000002", "Age" = "26" },
{ "FirstName" = "Arslan", "LastName" = "Ahmer", "ID" = "000003", "Age" = "27" }]

Hope it will help!

Advertisements
This entry was posted in .NET C#. Bookmark the permalink.

2 Responses to C# – Using JavaScriptSerializer to convert objects to JSON

  1. What you meant by olist is studentList ???

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