2012-06-21 32 views
1

我有一個簡單的NSDictionary,我試圖通過返回的JSON從外部網站的數據填充。返回的JSON沒問題,但我無法獲取特定鍵的實際數據。JSON解析與NSDictionary和鍵值查找值

這是打印到控制檯的JSON數據。

這是我的JSON數據:

(
     { 
     CategoryID = 12345; 
     CategoryName = "Baked Goods"; 
    }, 
     { 
     CategoryID = 12346; 
     CategoryName = Beverages; 
    }, 
     { 
     CategoryID = 12347; 
     CategoryName = "Dried Goods"; 
    }, 
     { 
     CategoryID = 12348; 
     CategoryName = "Frozen Fruit & Vegetables"; 
    }, 
     { 
     CategoryID = 12349; 
     CategoryName = Fruit; 
    }, 
     { 
     CategoryID = 12340; 
     CategoryName = "Purees & Soups"; 
    }, 
     { 
     CategoryID = 12341; 
     CategoryName = Salad; 
    }, 
     { 
     CategoryID = 12342; 
     CategoryName = "Snack Items"; 
    }, 
     { 
     CategoryID = 12343; 
     CategoryName = Vegetables; 
    } 
) 

我得到的錯誤是:

終止應用程序由於未捕獲的異常 'NSInvalidArgumentException' 的,理由是:「 - [__ NSCFArray enumerateKeysAndObjectsUsingBlock: ]:無法識別的選擇發送到 實例0x6884000'

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 

    NSError *error = nil; 
    // Get the JSON data from the website 
    NSDictionary *categories = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

    if (categories.count > 0){ 
     NSLog(@"This is my JSON data %@", categories); 

     [categories enumerateKeysAndObjectsUsingBlock: ^(__strong id key, __strong id obj, BOOL *stop) { 
     NSLog(@"Key = %@, Object For Key = %@", key, obj); }]; 
} 

我不知道爲什麼會發生這種情況,但我確定這很簡單,就像我使用不正確的對象或其他東西。

幫助表示讚賞。

+0

嘗試從錯誤中解決問題。它會告訴你你需要的一切。 – hooleyhoop

回答

4

+JSONObjectWithData:options:error:正在返回一個NSArray而非NSDictionary。 '-[__NSCFArray enumerateKeysAndObjectsUsingBlock:]是錯誤消息的關鍵部分。它告訴你,你在一個數組上調用-enumerateKeysAndObjectsUsingBlock:


對於這種情況,您可以改爲使用-enumerateObjectsUsingBlock:

如果你不能確定閹一個的NSArray或NSDictionary的將被退回,您可以使用-isKindOf:

id result = [NSJSONSerialization …]; 
if ([result isKindOf:[NSArray class]]) { 
    NSArray *categories = result; 
    // Process the array 
} else if ([result isKindOf:[NSDictionary class]]) { 
    NSDictionary *categories = result; 
    // Process the dictionary 
} 

enumerateObjectsUsingBlock:

執行使用的每個對象的給定塊數組,從第一個對象開始,繼續貫穿數組到最後一個對象。

  • (無效)enumerateObjectsUsingBlock:(無效(^)(ID OBJ,NSUInteger IDX,BOOL *停止))塊

因此,它應該被稱爲這樣

[categories enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    NSLog(@"index = %d, Object For Key = %@", idx, obj); 
}]; 

快速閱讀文檔確實可以爲您節省很多挫折。

+0

謝謝,我以前見過isKindOfClass,這當然有幫助。我把代碼放在NSArray裏面,現在我得到了一個不同的錯誤... – brianhevans

+0

謝謝,我之前看到了isKindOfClass,這當然有幫助。我把代碼放在NSArray中,現在我得到了一個不同的錯誤...不相容的塊指針類型發送'void(^)(__ strong id,__strong id,BOOL *)'到類型'void(^)(__ strong id,NSUInteger,BOOL *)'的參數''我知道第二個參數,但它期望什麼無符號整數值?我只是試圖迭代所有鍵和它們相關的值的數組。 – brianhevans

+0

謝謝,我對iOS完全陌生。我發現文檔有點黑洞。一旦我明白爲什麼某些東西不能正常工作,我就會看到使用這些文檔......無論如何,謝謝。 – brianhevans