在字典和数组的帮助下显示JSON数据

时间:2013-04-20 14:22:09

标签: nsdictionary nsjsonserialization

我收到以下错误

    [__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x75a8e20
    2013-04-20 08:56:14.90 MyApp[407:c07] *** Terminating app due to uncaught 
    exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: 
    unrecognized selector sent to instance 0x75a8e20'

这是我第一次使用JSON。当我尝试运行URL为flickr url的第一段代码时,我得到上述错误。当我使用照片作为按键时,它会打印数组并突然退出应用程序。

#define flickrPhotoURL [NSURL URLWithString: @"http://api.flickr.com/services/rest/?format=json&sort=random&method=flickr.photos.search&tags=rocket&tag_mode=all&api_key=12345&nojsoncallback=1"]

- (void)viewDidLoad
{
   [super viewDidLoad];
   //this line of code will be executed in the background to download the contents of the flickr URL
   dispatch_async(flickrBgQueue, ^{
   NSData* flickrData = [NSData dataWithContentsOfURL:flickrPhotoURL]; //NOTE: synchronous method...But we actually need to implement asynchronous method
   [self performSelectorOnMainThread:@selector(appFetchedData:) withObject:flickrData waitUntilDone:YES]; //when data is available "appFetchedData" method will be called
});

}

- (void)appFetchedData: (NSData *)responseData 
{
 //parsing JSON data
 NSError *error_parsing;
 NSDictionary *flickr_json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_parsing];
 NSArray* photo_information = [flickr_json objectForKey:@"photos"];

 NSLog(@"Photo Information: %@",photo_information);

 NSDictionary* photo = (NSDictionary*)[photo_information objectAtIndex:0];

 humanReadable.text = [NSString stringWithFormat:@"Owner is %@",[photo objectForKey:@"Owner"]];
}

但是当我通过用“贷款”替换关键“照片”来运行相同的代码时,使用以下URL和代码

#define flickrPhotoURL [NSURL URLWithString: @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]


- (void)appFetchedData: (NSData *)responseData 
{
 //parsing JSON data
 NSError *error_parsing;
 NSDictionary *flickr_json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_parsing];
 NSArray* photo_information = [flickr_json objectForKey:@"loans"];

 NSLog(@"Photo Information: %@",photo_information);

 NSDictionary* photo = (NSDictionary*)[photo_information objectAtIndex:0];

 humanReadable.text = [NSString stringWithFormat:@"loan amount is %@",[photo objectForKey:@"loan_amount"]];

}

,应用程序在humanredable.text属性上设置正确的信息。我是否使用了错误的密钥用于第一个JSON?

1 个答案:

答案 0 :(得分:2)

首先,感谢您按原样发布您的Flickr API密钥!对我来说,某天进行身份盗窃对我来说非常有用。

第二,非常感谢你没有阅读你收到的数据。它是这样开始的:

{"photos":{"page":1, "pages":1792, "perpage":100,
 ^^^^^^^^^^

因此,键photos的对象是字典,而不是数组,因此,

NSArray* photo_information = [flickr_json objectForKey:@"photos"];

错了。你的意思是:

NSArray* photo_information = [[flickr_json objectForKey:@"photos"]
                               objectForKey:@"photo"];

?此外,下面当您构造人类可读的描述时,

[photo objectForKey:@"Owner"]

错了,应该是

[photo objectForKey:@"owner"]

代替。