将以下类属性转换为Json格式

时间:2013-09-11 08:51:44

标签: c# asp.net json

我需要以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

2 个答案:

答案 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 参考

添加参考此链接

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