- [__ NSCFDictionary objectAtIndex:]:发送到实例的无法识别的选择器

时间:2013-09-24 10:54:08

标签: objective-c json unrecognized-selector

这是我的代码:

NSString *url = @"https://www.googleapis.com/language/translate/v2?key=API&q=hello%20world&source=en&target=de";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSLog(@"%@",request);

NSData *response = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:nil
                                                         error:nil];
NSLog(@"%@",response);
NSError *jsonParsingError = nil;
NSArray *retrievedJTrans = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSLog(@"%@",retrievedJTrans);
NSDictionary *translation;
for(int i=0; i<[retrievedJTrans count];i++)
{
    translation=[retrievedJTrans objectAtIndex:i];
    NSLog(@"Statuses: %@", [translation objectForKey:@"translatedText"]);
}
NSLog(@"%@",[translation class]);

我正在尝试从这个简单的JSON中检索翻译的文本:

{
    "data": {
        "translations": [
            {
                "translatedText": "Hallo Welt"
            }
        ]
    }
}

但我收到错误:

-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance

感谢任何帮助。使用最新的Xcode。

2 个答案:

答案 0 :(得分:2)

见这一行:

NSArray *retrievedJTrans = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];

您假设返回给您的JSON是一个数组,但错误消息告诉您它是一个NSDictionary。你可以使用的一点测试是:

id receivedObject = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
if ([receivedObject isKindOfClass:[NSDictionary class]]) {
    // Process the object as a dictionary
} else {
    // Process the object as an array
}

答案 1 :(得分:0)

NSArray *retrievedJTrans = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];

是字典

你可能想要什么

NSDictionary *retrievedJTransD = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSArray *retrievedJTrans = retrievedJTransD[@"data"][@"translations"];