2015-07-20 38 views
0

我的代碼如下:如何在.net webservice中顯示數組內的JSON輸出?

[{"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":"[email protected]"}] 

但我想產生這樣的輸出:

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

陣列

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)); 
     } 
    } 
} 

}這樣

據生成輸出內部陣列。所以我怎樣才能產生這樣的輸出使用var list = new List>(); NET中的 webservice

回答

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; } 
} 

最後這個會給你「數組裏面的數組結構」。