-1

我需要将以下Employee.cs类转换为 json 格式,为此我编写了以下代码 //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 输出

4

2 回答 2

3

我会使用JSON.NET序列化器,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"
  }
]
于 2013-09-11T08:59:35.503 回答
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参考

添加参考此链接

http://matijabozicevic.com/blog/csharp-net-development/csharp-serialize-object-to-json-format-using-javascriptserialization

于 2013-09-11T09:01:09.500 回答