2011-09-19 54 views
0

我正在使用WebMethod將JSON對象返回給JavaScript。我已經能夠成功地使用List來做到這一點。我現在需要嵌套列表,所以我得到:商店列表<Hashtable>在列表<Hashtable>中返回JSON

{ 
    "SUCCESS":1, 
    "USERS":[ 
     {"NAME":"Michael", "AGE":10}, 
     {"NAME":"Michael", "AGE":10} 
    ] 
} 

我的代碼一言以蔽之:

Hashtable ht = new Hashtable(); 
List<Hashtable> HashList = new List<Hashtable>(); 
List<Hashtable> HashListUsers = new List<Hashtable>(); 

ht.Add("SUCCESS", 1); 
ht.Add("USERS", HashListUsers); 
HashList.Add(ht); 

return HashList; 

我以爲我可以在主列表存儲列表做到這一點。

我怎麼會用WebMethod獲得嵌套的JSON對象?

回答

3

你可以使用一個視圖模型:

public class Result 
{ 
    public int Success { get; set; } 
    public User[] Users { get; set; } 
} 

public class User 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

,然後有一個WebMethod:而不是使用一個列表 使用類

[WebMethod] 
public Result Foo() 
{ 
    return new Result 
    { 
     Success = 1, // a boolean seems more adapted for this instead of integer 
     Users = new[] 
     { 
      new User { Name = "Michael", Age = 10 }, 
      new User { Name = "Barbara", Age = 25 }, 
     } 
    }; 
} 
+0

所以,如果我理解正確的話。該類的屬性(名稱,年齡等)將被序列化爲嵌套的JSON對象? –

+0

@Michael C.蓋茨,你理解正確。 –

+0

對於Users = new []:如何從數據庫添加用戶?我正在使用一個foreach(dataTable.rows中的DataRow dr),遍歷每條記錄。我如何將此添加到用戶[]數組? –