-6

这是我的代码:

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。

4

2 回答 2

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
}
于 2013-09-24T11:01:42.847 回答
0
NSArray *retrievedJTrans = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];

是一本字典

你可能想要什么

NSDictionary *retrievedJTransD = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSArray *retrievedJTrans = retrievedJTransD[@"data"][@"translations"];
于 2013-09-24T11:02:57.450 回答