2013-09-24 1 views
-6

Вот мой код:- [__ NSCFDictionary objectAtIndex]: непризнанные селектор направлен например

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

простофиля многих других ... ваш JSON является ДИКТ не массив –

+0

В вашем словаре нет индексов. В общем, есть хорошая идея проверить класс объектов, которые выходят из сериализации json. –

+0

См. Json.org и изучите синтаксис JSON. –

ответ

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

является словарь

что вы можете

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

вздох ... @downvoter: почему? –

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 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^