2

我正在尝试解析来自 reddit.com 的 JSON 提要,然后将其显示在表格视图中。JSON 看起来像这样:

{
kind: Listing
data: {
modhash: 3lmt2d4hq6797af804da91bde566bd067ddee68e1e7f8e0dda
children: [
{
kind: t3
data: {
domain: imgur.com
banned_by: null
media_embed: { }
subreddit: funny
selftext_html: null
selftext: 
likes: null
link_flair_text: null
id: 16e9so
clicked: false
title: I left my dog unattended with the 2 year old...
num_comments: 166
score: 2213
approved_by: null
over_18: false
hidden: false
thumbnail: http://c.thumbs.redditmedia.com/DaoiOlvtdjaPBG3n.jpg
subreddit_id: t5_2qh33
edited: false
link_flair_css_class: null
author_flair_css_class: null
downs: 2481
saved: false
is_self: false
permalink: /r/funny/comments/16e9so/i_left_my_dog_unattended_with_the_2_year_old/
name: t3_16e9so
created: 1357963292
url: http://imgur.com/zGMxP
author_flair_text: null
author: ShaneNickerson
created_utc: 1357934492
media: null
num_reports: null
ups: 4694
}
...more items here
}

这是我的 tableview 控制器代码:

    #import "mainRedditFunViewController.h"
    #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

    #define kjsonURL [NSURL URLWithString: @"http://reddit.com/r/funny/.json"
@interface mainRedditFunViewController ()

@end

@implementation mainRedditFunViewController

- (void)viewDidLoad

{

    [super viewDidLoad];

    dispatch_async(kBgQueue, ^{

        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://reddit.com/r/funny/.json"]];

        [self performSelectorOnMainThread:@selector(fetchedData:)
                               withObject:data waitUntilDone:YES];

    });

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    // Return the number of sections.

    return 1;

}
- (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] ;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    NSDictionary *appsdict = [jsonResults objectAtIndex:indexPath.row];

    NSString *VersionString = [appsdict objectForKey:@"url"];

    NSString *priceString = [appsdict objectForKey:@"author"];

    NSURL *imageURL = [NSURL URLWithString:[appsdict objectForKey:@"thumbnail"]];

    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

    UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];

    cell.textLabel.text = [appsdict objectForKey:@"title"];

    cell.detailTextLabel.text = [NSString stringWithFormat:@"URL: %@ Author: $ %@ USD",VersionString,priceString];

    cell.imageView.image = imageLoad;

    return cell;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    // Return the number of rows in the section.

    return [jsonResults count];

}


- (void)fetchedData:(NSData *)responseData {

    NSError* error;

    NSDictionary* json = [NSJSONSerialization

                          JSONObjectWithData:responseData

                          options:kNilOptions

                          error:&error];

    jsonResults = [json objectForKey:@"data.children"];

    [self.tableView reloadData];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

但是,输出完全为空。无论如何我可以解决它吗?我之前用另一个(较小的)提要尝试过,效果很好。我确定我是否正确地进行了 JSONPath 格式设置,因为我看起来像这样:

-kind
 ->data
  ->children
    ->data (my items)
    ->data
    ->data
    ...

我会很感激我得到的任何帮助!

4

1 回答 1

1

对不起,这个答案来晚了!希望还是需要的。。。

我稍微修改了您的代码以访问返回的 Json 结果的子级别。

您当然有正确的想法,但只需要在您的 fetchedData 方法中添加一些字典。如果您在 NSJSONSerialization 下的方法中添加这些字典;

 NSDictionary* json = [NSJSONSerialization

                      JSONObjectWithData:data

                      options:kNilOptions

                      error:&error];

//NSArray *Fullarray = [[NSArray alloc] initWithObjects:json, nil];

_jsonResult = [[NSMutableArray alloc] init];

NSDictionary *dataDict = [json objectForKey:@"data"];
NSDictionary *chilrenDict = [dataDict objectForKey:@"children"];

for (NSDictionary *informationFromChild in chilrenDict) {
    NSLog(@"chil %@", chilrenDict);
    [_jsonResult addObject:chilrenDict];
}

然后在您的 tableView cellForRow 中将您的 appsDict 更改为此

NSDictionary *appsdict = [[_jsonResult objectAtIndex:indexPath.row] objectForKey:@"data"];

那应该修复代码并填充tableView ...您也可以通过检查来对此进行检查

NSLog(@"count %i", [_jsonResult count]);

表格视图中填充的数据

让我知道这是否有帮助,快乐的编码。吨

于 2013-03-03T10:52:55.347 回答