【问题标题】:Convert following class properties into Json format将以下类属性转换为 Json 格式
【发布时间】:2013-09-15 05:03:14
【问题描述】:

我需要将以下 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输出

【问题讨论】:

    标签: c# asp.net json


    【解决方案1】:

    我会使用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"
      }
    ]
    

    【讨论】:

    • 能否详细发送该代码。如何添加 NuGet 包 JSON.NET 包。如何包含在命名空间中............您可以详细说明一下
    【解决方案2】:
    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

    【讨论】:

      猜你喜欢
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      相关资源
      最近更新 更多