应用程序保持崩溃 - JSON

时间:2012-07-15 05:32:12

标签: iphone objective-c xcode json ipad

我试图使用JSON解析来自雅虎财经的数据。由于某种原因,应用程序不断崩溃。似乎最后一行代码导致了崩溃。当我评论该线路时,不会发生崩溃。这就是我到目前为止所有的想法......

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:     @"http://query.yahooapis.com/v1/public/yql?    q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)%0A%09%09&env    =http%3A%2F%2Fdatatables.org%2Falltables.env&format=json"] //2

#import "JsonViewController.h"

@implementation JsonViewController

- (void)viewDidLoad
{
[super viewDidLoad];

dispatch_async(kBgQueue, ^{
    NSData* data = [NSData dataWithContentsOfURL: 
                    kLatestKivaLoansURL];
    [self performSelectorOnMainThread:@selector(fetchedData:) 
                           withObject:data waitUntilDone:YES];
});
}

- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization 
                      JSONObjectWithData:responseData //1

                      options:kNilOptions 
                      error:&error];

NSArray* latestLoans = [json objectForKey:@"query"]; //2

NSLog(@"query: %@", latestLoans); //3

NSDictionary* loan = [latestLoans objectAtIndex:0]; /////// Where crash happens //////
}
@end

这是控制台中的错误消息

  

[__ NSCFDictionary objectAtIndex:]:无法识别的选择器发送到实例0x6a65420   2012-07-15 01:18:29.492 Json [1730:f803] * 由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [__ NSCFDictionary objectAtIndex: ]:无法识别的选择器发送到实例0x6a65420'

2 个答案:

答案 0 :(得分:2)

您正尝试将objectAtIndex:发送到NSDictionary。当你在做什么

NSArray* latestLoans = [json objectForKey:@"query"]; //2

[json objectForKey:@"query"]返回'NSDictionary'而不是NSArray。你可以通过

来看到这一点
NSLOG(@"CLASS is %@ ",[latestLoans Class]);

在“NSArray * latestLoans = [json objectForKey:@”query“]之后;”声明。在解析之前仔细检查您的JSON字符串。当您将json解析时,您将获得更详细的答案。

答案 1 :(得分:2)

这是因为您的JSON正在解码为NSDictionary而不是NSArray。如果我正确看到了雅虎的回复,您可能想要获取objectForKey:@"results"然后objectForKey:@"quote"

NSDictionary *resultQuery = [json objectForKey:@"query"];
NSDictionary *results = [resultQuery objectForKey:@"results"];
NSDictionary *quote = [resultQuery objectForkey@"quote"];

这就是您发布的网址上的JSON的结构:

{"query": {
     "count":1,
     "created":"2012-07-15T05:48:29Z",
     "lang":"en-US",
     "results":{
         "quote":{
               "symbol":"AAPL","Ask":"605.00"
                 }
               }
           }
}

当然,您需要将其扩展为正确的验证步骤,但关键是要知道返回JSON的实际内容(我查看了您的URI,并且在任何地方都没有数组)。