我已经尝试了几次,但我仍然没有得到如何进入JSON提要并检索我需要抓取的内容。
Feed看起来像这样,在我的代码中我试图取出所有的标题。我不知道如何进入Json Feed。
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:@"http://api.storageroomapp.com/accounts/511a4f810f66026b640007b8/collections/511a51580f66023bff000ce9/entries.json?auth_token=Zty6nKsFyqpy7Yp5DP1L&preview_api=1"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view from its nib.
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
data = [[NSMutableData alloc] init];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{
[data appendData:theData];
}
-(void)connectionDidFinishLoading:(NSURLConnection *) connection{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
[mainTableView reloadData];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The data could not be downloaded - please make sure you're connected to either 3G or Wi-FI" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
-(int)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [news count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"title"];
}
return cell;
}
在我的.H我有NSArray *新闻;和NSMutableData *数据。
任何帮助都会很棒,请你清楚地解释一下你的自我,因为我是这种语言的新手。
答案 0 :(得分:2)
查看您在代码中使用的逻辑以及您发布的示例JSON,看起来您的数组看起来不像您想要的那样。
最初,JSON采用字典的形式(因此您提供的图像中有花括号)。因此,您应该将JSON的初始解析调整为如此:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
从这里,您可以从字典中接收密钥。你要找的那个是“数组”,尽管它的名字实际上也是一本字典。
NSDictionary *arrayDictionary = dictionary[@"array"];
向右移动,您最终可以访问您正在查找的“资源”数组,并且可以将其存储在您在.h文件中创建的实例变量中。
news = arrayDictionary[@"resources"];
现在,在cellForRowAtIndexPath
方法中,您可以根据提供给您的索引路径行访问此数组的各种元素。
NSDictionary *newsItem = news[[indexPath row]];
最后,您可以访问各种属性,例如该新闻项目中的标题,并设置文本标签的文本。
NSString *title = newsItem[@"title"];
[[cell textLabel] setText:title];