JSON to C# object to JSON – System.Web.Script.Serialization.JavaScriptSerializer

Posted: May 13, 2011 in JSON, Performance
Tags: , ,

Use JavaScriptSerializer to convert JSON object to C# object and backwards. It is very useful to build AJAX based web pages for thinner network traffic and for better client side html computation …

using System.Web.Script.Serialization;

public class Employee
 public string Name { get; set; }
        public string Age { get; set; }
        public string ID { get; set; }

Employee oEmployee1 = new Employee { Name = “name1”, ID = “1”, Age = “5” };
Employee oEmployee2 = new Employee { Name = “name2”, ID = “2”, Age = “7” };
Employee oEmployee3 = new Employee { Name = “name3”, ID = “3”, Age = “8” };
List<Employee> oList = new List<Employee>() { oEmployee1, oEmployee2, oEmployee3 };

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
List<Employee> oNewList = (List<Employee>)oSerializer.Deserialize(sJSON, typeof(List<Employee>));
Response.Write(oNewList.Count + “”);

string sJSON2 = oSerializer.Serialize(oEmployee1);
Employee emp = (Employee)oSerializer.Deserialize(sJSON2, typeof(Employee));
Response.Write(emp.Name + “”);

  1. Suma says:

    Is it possible to use System.Web.Script.Serialization in c# winforms application?

  2. scmay says:

    Hi, I am having issues trying to get reference to

    using System.Web.Script.Serialization.JavaScriptSerializer;
    I have added System.Web.Extensions (version 4) and am using Visual Studio 2010. Visual Studio is throwing error of not recognizing the library.

  3. mnea says:

    Thank you for the example. I had been working on trying to deserialize json data returned from a restful webAPI and could not find an example that returned or parsed multiple enteries into a list. This answered my question. Wonderful work!

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s