2013-09-24 38 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 
} 
相關問題