Convert objects to JSON in C# using JavaScriptSerializer

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:

想对作者说点什么? 我来说一句