[英]Parse a JSON array of dictionaries in a tableview
我被困在將字典的 JSON 數組(http://www.cjs-design.nl/json.php)解析為表格視圖的時候。 我只想顯示標題的第一個,稍后會弄清楚詳細視圖。
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSString *rawJson = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.cjs-design.nl/json.php"]];
// No connection or file not found
if ([rawJson length] == 0) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Foutmelding" message:@"De URL kon niet worden gevonden" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
[rawJson release];
return;
}
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
// 1. get the top level value as a dictionary
NSDictionary *jsonObject = [parser objectWithString:rawJson error:NULL];
// 2. get the object as an array
NSArray *list = [jsonObject objectForKey:@"book"];
// 3. iterate the array; each element is a dictionary.
for (NSDictionary *book in list)
{
// that contains a string for the key "title"
NSString *title = [book objectForKey:@"title"];
cell.textLabel.text = title;
}
return cell;
}
在某個地方,即 viewDidLoad,您需要解析您的 JSON。 然后實現 UITableView 的 dataSource 方法。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [list count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *book = [list objectAtIndex:indexPath.row];
NSString *title = [book objectForKey:@"title"];
cell.titleLabel.text = title;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *rawJson = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.cjs-design.nl/json.php"]];
// No connection or file not found
if ([rawJson length] == 0) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Foutmelding" message:@"De URL kon niet worden gevonden" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
[rawJson release];
return;
}
SBJsonParser *parser = [[SBJsonParser alloc] init];
// 1. get the top level value as a dictionary
NSDictionary *jsonObject = [parser objectWithString:rawJson error:NULL];
NSLog(@"Dict: %@",jsonObject);
list = [jsonObject objectForKey:@"book"];
NSLog(@"List: %@",list);
[rawJson release];
}
當我 NSlog 他們時,他們都打印 Null,所以字符串沒有被解析? 該字符串包含 arrays 的字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.