2017-07-17 93 views
0

在某些情況下,我嘗試解析的JSON對象包含某個鍵。在其他情況下,它不會。IOS/Objective-C:檢測jsonResults是否包含鍵值對

當我嘗試訪問對象的鍵值對時,不管鍵是否存在,它自然會導致崩潰。因此,我試圖事先測試密鑰是否存在。但是,由於某種原因,NSNull類測試不起作用。有人可以建議使用正確的測試來檢測鑰匙是否存在?

這是我editied代碼篩選出無效的情況下,它是不工作:

NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
     NSLog(@"Results of post: %@", jsonResults); 

if ([jsonResults[@"response"][@"insert_id"]isKindOfClass:[NSNull class]]){ 
        NSLog(@"insert id is null");} 
else { 
//EVEN WHEN I KNOW THAT THERE IS no insert_id key, I get to this code suggesting test above not working 
    //Access insert_id value using Key value and so something with it 
NSInteger insertID = [jsonResults[@"response"][@"insert_id"] integerValue]; 
    } 
+0

什麼崩潰說呢? –

+0

__NSCFString objectForKeyedSubstrict:]:發送到實例 – user6631314

+0

的無法識別的選擇器看起來像jsonResults [@「response」]是一個字符串,但不是字典! –

回答

0

在它是一個NSDictionary結束時,如果你研究的NSDictionary是否包含鍵,你會發現更多的幫助。

objectForKey如果一個鍵不存在,將返回nil。 你可以嘗試使用:

if ([jsonResults objectForKey:@"response"] valueForKey:@"insert_id"] != nil { 
    NSLog(@"insert id is not null"); 
} 

或以確保你的反應是一本字典

NSDictionary *response = jsonResults[@"response"]; 
if ([response isKindOfClass:[NSDictionary class]]) { 
    if (jsonResults[@"response"][@"insert_id"] != nil { 
    NSLog(@"insert id is not null"); 
    } 
}