您的位置:首页 > 移动开发 > Objective-C

Convert objects to JSON in C# using JavaScriptSerializer

2010-05-25 20:52 519 查看
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"}]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: