2011-10-25 71 views
2

我有JSON數據是這樣的:UITableView的部分

[{"id":"3","name":"jason"},{"id":"4","name":"karen"}] 

我想建立與每對[ID,名稱]的截面的表格視圖。該部分標題應該是id值,每個部分的唯一單元格應該是名稱的值。

如何將JSON數據解析爲數組並使用[數組數]來確定需要顯示多少節?

非常感謝..

原諒我的英文不好!

+0

感謝Mr.Wizard我的編輯器! – Jason

回答

4

落實UITableViewDatasource以下方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return [JSONArray count]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    return 1; 
} 

要設置一節的標題值:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    return [[JSONArray objectAtIndex:section] objectForKey:@"id"]; 
} 

要設置單元格的值實現UITableViewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
     cell.textLabel.text = [[JSONArray objectAtIndex:indexPath.section] objectForKey:@"name"]; // set the cell's text here 
    } 
    return cell; 
} 

僅供參考檢查UITableViewDataSourceUITableViewDelegate

+0

你是好男人,謝謝!你的代碼非常有用。 – Jason

1

看看這個項目。它是一種框架,使用JSON工作: https://github.com/stig/json-framework/

針對此框架教程,可以發現: http://iosdevelopertips.com/networking/iphone-json-flickr-tutorial-part-1.html

框架增加了一個類別的NSString。與該類別可以解析JSON數據到一個NSArray的(對象爲您的示例清單)或NSDictionary中(某些物體或結構):

#import "JSON.h" 
... 
NSString jsonString = //get your JSON from somewhere 
NSArray * array = [jsonString JSONValue]; 

我希望我可以給你的印象,做什麼爲了實現你的目標。更多信息請參閱JSON項目的教程或所提到的教程。

如何從JSON陣列建一個表是在回答:UITableView sections from JSON data

+0

非常感謝! – Jason