我需要以json格式转换以下 Employee.cs 类,因为我编写了以下代码 //Employee.cs(在类文件中)
public class Employee
{
public string Name { get; set; }
public string Job { get; set; }
public string City { get; set; }
}
//在我的MyPage.aspx页面
Employee oEmployee1 =
new Employee { Name = "Pini", Job = "111", City = "30" };
Employee oEmployee2 =
new Employee { Name = "Yaniv", Job = "Developer", City = "Hyd" };
Employee oEmployee3 =
new Employee { Name = "Yoni", Job = "Developer", City = "Bglre" };
List<Employee> oList = new List<Employee>() { oEmployee1, oEmployee2, oEmployee3 };
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
Response.Write("<pre>"+sJSON+"</pre>");
我得到了以下输出:
[{"Name":"Pini","Job":"111","City":"30"},{"Name":"Yaniv","Job":"Developer","City":"Hyd"},{"Name":"Yoni","Job":"Developer","City":"Bglre"}]
是否有任何其他方式可以更有效地转换为json格式,我想美化json输出
此致 Chandu
答案 0 :(得分:2)
我会使用JSON.NET Serializer和Formatting.Indented
,如下所示
string result= JsonConvert.SerializeObject(obj, Formatting.Indented);
<强>输出强>
[
{
"Name": "Pini",
"Job": "111",
"City": "30"
},
{
"Name": "Yaniv",
"Job": "Developer",
"City": "Hyd"
},
{
"Name": "Yoni",
"Job": "Developer",
"City": "Bglre"
}
]
答案 1 :(得分:0)
list<Employee> oEmployee=
{
new Employee() { Name = "Pini", Job = "111", City = "30" },
new Employee() { Name = "Pini", Job = "111", City = "30" },
new Employee() { Name = "Pini", Job = "111", City = "30" },
};
var oSerializer=new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
Response.Write("<pre>"+sJSON+"</pre>");
添加 System.Web.Script.Serialization 参考
添加参考此链接