2012-06-21 31 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