Introduction
JavaScriptSerializer provides serialization and deserialization functionality for AJAX based applications. Its basically serilize and deserilize the .NET objects to JSON Format.
JavaScriptSerializer is an inbuilt class from .NET framework class library under system.web.Script.serialization namespace(System.Web.Extensions.dll) and it is avalible from .NET 3.5 version onwards.
In the below example we will try to convert .NET object to JSON using JavaScriptSerializer.Serialize method and JSON to .NET object using JavaScriptSerializer.Deserialize method.
Sample Program:
public class Student
{
public int RollNo { get; set; }
public string Name { get; set; }
public int Marks { get; set; }
}
class DotNETObject2JSON
{
static void Main(string[] args)
{
//creating sample student ojects
Student obj1 = new Student { RollNo = 1, Name = "A", Marks = 10 };
Student obj2 = new Student { RollNo = 2, Name = "B", Marks = 20 };
Student obj3 = new Student { RollNo = 3, Name = "C", Marks = 30 };
Student obj4 = new Student { RollNo = 4, Name = "D", Marks = 40 };
//adding student objects to list
List<Student> objStudentList = new List<Student>() { obj1, obj2, obj3, obj4 };
System.Web.Script.Serialization.JavaScriptSerializer objJSSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//Serialization .NET Object to JSON
string strJSON = objJSSerializer.Serialize(objStudentList);
//De-serialization JOSON to .NET Object to JSON
List<Student> listStudent = objJSSerializer.Deserialize<List<Student>>(strJSON);
//Serialization single student Object to JSON
string strSingleStudentJSON = objJSSerializer.Serialize(obj1);
//De-Seralization JOSON to single student Object
Student listStudent0 = objJSSerializer.Deserialize<Student>(strSingleStudentJSON);
}
}
output:
Serialization of list object is : [{"RollNo":1,"Name":"A","Marks":10},
{"RollNo":2,"Name":"B","Marks":20},
{"RollNo":3,"Name":"C","Marks":30},
{"RollNo":4,"Name":"D","Marks":40}]
Serialization of student object is: {"RollNo":1,"Name":"A","Marks":10}{"RollNo":1,"Name":"A","Marks":10}
De-Serialization output will be list<student> object and student object.
References
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx