2011-09-19 5 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

만약 내가 제대로 이해하고 있습니다. 클래스 (Name, Age 등)의 속성은 중첩 된 JSON 객체로 직렬화됩니까? –

+0

@Michael C. Gates, 귀하는 올바르게 이해합니다. –

+0

사용자 = new [] : 데이터베이스의 사용자를 추가하려면 어떻게합니까? 각 레코드를 반복하면서 foreach (DataTable.rows의 DataRow dr)를 사용하고 있습니다. 이걸 Users [] 배열에 어떻게 추가합니까? –