无法解析json

时间:2012-02-07 10:48:18

标签: objective-c ios cocoa-touch ios5 nsdictionary

我试图解析twitter返回的json。 json被很好地检索并将其转换为NSDictionary,

字典对象上的NSLog运行良好并显示所有推文。

NSLog(@"Twitter response: %@", dict);

但是当我尝试为dict对象中的任何键获取objectForKey时出现以下错误:

  

2012-02-07 15:35:28.988 TestTweetApp [1525:12103] - [__ NSCFArray   objectForKey:]:无法识别的选择器发送到实例0x6a2a370   [切换到处理1525线程0x12103] [切换到处理1525   线程0x12103] 2012-02-07 15:35:28.997 TestTweetApp [1525:12103] *   由于未捕获的异常而终止应用程序   'NSInvalidArgumentException',原因:' - [__ NSCFArray objectForKey:]:   无法识别的选择器发送到实例0x6a2a370'   * 第一次抛出调用堆栈:(0x176e052 0x1a40d0a 0x176fced 0x16d4f00 0x16d4ce2 0x3044 0xd306 0x2048445 0x2049ecf 0x2049d28 0x20494af   0x9ca1fb24 0x9ca216fe)终止调用throw   exceptionsharedlibrary apply-load-rules all

viewDidLoad()函数的代码是:

- (void)viewDidLoad
{
    [super viewDidLoad];

    TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString: @"https://api.twitter.com/1/statuses/public_timeline.json?screen_name=[SOME_USER_NAME]&include_entities=true"] parameters:nil requestMethod:TWRequestMethodGET];

    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
    {
        if ([urlResponse statusCode] == 200) 
        {
            NSError *error;  

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];

            NSLog(@"Twitter response: %@", [dict objectForKey:@"entities"]);
        }
        else
            NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
    }];

}

2 个答案:

答案 0 :(得分:2)

您的回复似乎是NSArray而不是NSDictionary。试试

NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error]);

之前

NSDictionary *dict... 

行并查看格式。 然后将其移动到NSArray并正确访问元素。

NSArray *response = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(@"elements = %@", response);

答案 1 :(得分:2)

如果您不确定响应格式或可能有多种可能的响应格式,并且还需要处理错误,则可以使用isKindOfClassrespondsToSelector等任何内省方法来确定由JSONObjectWithData返回的类型

id responseData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];

if([responseData respondsToSelector:@selector(objectForKey:)]){
   //Response is of type NSdictionary
   NSLog(@"Twitter response: %@", [responseData objectForKey:@"entities"]);
}else if ([responseData respondsToSelector:@selector(objectAtIndex:)]){
        //Response is of type NSArray
      }
      else{
         // error 
      }