0

我正在尝试使用 JSON 解析来自 yahoo Finance 的数据。由于某种原因,该应用程序不断崩溃。似乎最后一行代码导致了崩溃。当我注释掉该行时,不会发生崩溃。这是我到目前为止所拥有的......有什么想法吗?

#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'

4

2 回答 2

2

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

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

返回一个 'NSDictionary'而[json objectForKey:@"query"]不是NSArray. 你可以通过这样做看到这一点

NSLOG(@"CLASS is %@ ",[latestLoans Class]);

"NSArray* latestLoans = [json objectForKey:@"query"];"之后 陈述。在解析之前仔细检查您的 JSON 字符串。当您将要解析的 json 放入时,您将得到更详细的答案。

于 2012-07-15T05:51:35.733 回答
2

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

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

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

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

当然,您将希望将其扩展为适当的验证步骤,但关键是要知道返回的 JSON 内部实际包含什么(我查看了您的 URI,并且任何地方都没有数组)。

于 2012-07-15T05:54:36.223 回答