【问题标题】:App keeps Crashing - JSON应用程序不断崩溃 - JSON
【发布时间】:2012-07-14 10:29:56
【问题描述】:

我正在尝试使用 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 '

【问题讨论】:

  • 当您记录 latestLoans 时会打印什么?

标签: iphone objective-c xcode json ipad


【解决方案1】:

这是因为您的 JSON 正在解码为 NSDictionary 而不是 NSArray。如果我正确地看到了 yahoo 响应,您可能想要获取 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,发现任何地方都没有数组)。

【讨论】:

    【解决方案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 放入后,您会得到更详细的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      相关资源
      最近更新 更多