博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

Convert objects to JSON in C# using JavaScriptSerializer

Posted on 2010-05-25 20:52  codingsilence  阅读(264)  评论(0编辑  收藏  举报

Want to convert a C# object into it's JSON equivalent? Here is a simple object from the System.Web.Script namespace that does exactly that:

System.Web.Script.Serialization.JavaScriptSerializer . It is stored in the System.Web.Extentions DLL (.Net Framework 3.5 only)

Using this object we serialize and deserialize  objects in C#. Here is a quick sample:

A simple Employee object:

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

Adding some instances of them to a List:

Employee oEmployee1 = 
       new Employee{Name="Pini",ID="111", Age="30"};

Employee oEmployee2 = 
      new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };
Employee oEmployee3 = 
        new Employee { Name = "Yoni", ID = "Biton", Age = "20" };

List<Employee> oList = new List<Employee>() 
{ oEmployee1, oEmployee2, oEmployee3 };
 

Serializing then:

System.Web.Script.Serialization.JavaScriptSerializer oSerializer = 
         new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);

And here is the output:

[{"Name":"Pini","Age":"30","ID":"111"},
{"Name":"Yaniv","Age":"31","ID":"Cohen"},
{"Name":"Yoni","Age":"20","ID":"Biton"}]