如何在.net webservice中显示JSON输出,如数组内的数组?

时间:2015-07-20 09:34:14

标签: c# asp.net arrays json web-services

我的代码在下面:

public class WS_Login : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void Login(string userName, string password)
    {
        DAL.dbOperation dboperation = new DAL.dbOperation();
        dboperation.AddParameter("@EUserID", userName);
        dboperation.AddParameter("@CompID", Convert.ToString(balUserlogin.m_Ds.Tables[0].Rows[0]["CompanyID"]));
        DataSet ds = dboperation.getDataSet("Mobile_sp_tbl_Employee_Select_Fullinfo");
        if (ds.Tables[0].Rows.Count > 0)
        {
            string[] selectedColumns = new[] { "EmployeePhoto", "EmployeeID", "EmpName", "EmployeementDate", "EDateOfBirth", "StateName", "BranchName", "CategoryName", "SubCatName", "DepartmentName", "DesignationName", "PaycaderName", "EProbation", "ECompanyEmail" };
            DataTable dt = new DataView(ds.Tables[0]).ToTable(false, selectedColumns);

            var list = new List<Dictionary<string, object>>();

            foreach (DataRow row in dt.Rows)
            {

                var dict = new Dictionary<string, object>();

                foreach (DataColumn col in dt.Columns)
                {
                    row[col] = row[col].ToString();
                    dict[col.ColumnName] = row[col];
                }
                list.Add(dict);
            }
            HttpContext.Current.Response.Write(new JavaScriptSerializer().Serialize(list));
        }
    }
}

}

正在生成这样的输出:

[{"EmployeePhoto":"1009-employee.jpg","EmployeeID":"1009","EmpName":"JOHN PATEL","EmployeementDate":"01 Aug 2003","EDateOfBirth":"02 Jan 1979","StateName":"Gujarat","BranchName":"Maintenance","CategoryName":"Staff","SubCatName":"Technical","DepartmentName":"Electrical and Electronics","DesignationName":"MANAGER (MAINT.)","PaycaderName":"M4","EProbation":"0","ECompanyEmail":"abc@manager.co"}]

但我想生成这样的输出:

{
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York"
  },
  "phoneNumber": [
    {
      "location": "home",
      "code": 44
    }
  ]
}

数组内部的数组。那么如何使用.NET webservice中的 var list = new List&gt;();

生成这样的输出

1 个答案:

答案 0 :(得分:0)

您的示例中的数组内部没有数组。卷曲支架用于结构。对于数组,JSON使用方括号。如果你想要结构内部结构,只需定义包含另一个类的类。如果你真的想要数组里面的数组,定义包含数组的类。

public class A
{
  public int aa { get; set; }
  public int ab { get; set; }
}


public class B
{
  public int ba { get; set; }
  public A bb { get; set; }
}

这将编码为“结构中的结构”。这个

public class A
{
  public int aa { get; set; }
  public int ab { get; set; }
}


public class B
{
  public int ba { get; set; }
  public A[] bb { get; set; }
}

会给你“数组内部结构”。

public class C
{
  public int ca { get; set; }
  public B[] cb { get; set; }
}

最后这个会给你“数组里面的数组结构”。