来自JSON的字典中的键

时间:2011-08-30 12:57:30

标签: ios json dictionary key

我正在导入JSON字典。我需要知道使用它的键的名称。

字典正在加载数据ok:

   - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];    
  NSDictionary *results = [responseString JSONValue];
  NSLog(@"tenga: %@",results);

但是当我尝试获取密钥的名称时,应用程序崩溃了:

NSArray * keys = [results allKeys];
NSLog(@"keys: %@",keys); ...}

错误消息:

  

[__ NSArrayM allKeys]:无法识别的选择器发送到实例0x5a16b30   2011-08-30 22:52:26.171 Twitter搜索[1906:207] * 由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [__ NSArrayM allKeys]:无法识别的选择器发送到实例0x5a16b30 “

为什么allKeys无效?

如何获取密钥的名称,以便开始处理对象?

修改

我正在使用http://code.google.com/p/json-framework Stig Brautaset json framework

3 个答案:

答案 0 :(得分:8)

您从JSON字符串获取的URL为您提供了一个数组,而不是一个对象,即它看起来像:

[ { "foo1" : "bar1" }, { "foo2" : "bar2" },... ]

注意括号[ ]。在这种情况下,您的JSON解析器为您提供了NSArray作为顶级(Objective-C)对象。你需要一些逻辑:

id results = [responseString JSONValue];
if ([results isKindOfClass: [NSArray class]])
{
    // probably iterate through whtever is in it
}
else if ([results isKindOfClass: [NSDictionary class]])
{
    // dictionary at the top level.  Hooray!
}
else
{
    // something went horribly wrong, deal with it.
}

答案 1 :(得分:2)

你在这里得到的结果不是NSDictionary,而是NSArray。 NSArray没有导致崩溃的allKeys选择器。如果您在正在使用的JSON框架上发布更多信息,我们可以帮助更好地解决问题

答案 2 :(得分:0)

发布日志表示此来电[responseString JSONValue]会返回NSArray