简体   繁体   English

来自JSON的字典中的键

[英]Keys in a dictionary from JSON

I'm importing a JSON dictionary. 我正在导入JSON字典。 I need to know the name of the keys to work with it. 我需要知道使用它的键的名称。

The dictionary is loading the data ok: 字典正在加载数据确定:

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

but when I try to get the names of the keys the app crashes: 但当我尝试获取键的名称时,应用程序崩溃:

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

error message: 错误信息:

[__NSArrayM allKeys]: unrecognized selector sent to instance 0x5a16b30 2011-08-30 22:52:26.171 Twitter Search[1906:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM allKeys]: unrecognized selector sent to instance 0x5a16b30' [__NSArrayM allKeys]:无法识别的选择器发送到实例0x5a16b30 2011-08-30 22:52:26.171 Twitter搜索[1906:207] *由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [__ NSArrayM allKeys]:无法识别的选择器发送到实例0x5a16b30'

Why is allKeys not working? 为什么allKeys都不工作?

How do I get the names for my keys so I can start working with the objects? 如何获取密钥的名称,以便开始处理对象?

edit 编辑

Im using the http://code.google.com/p/json-framework Stig Brautaset json framework 我正在使用http://code.google.com/p/json-framework Stig Brautaset json框架

The URL that you obtained that JSON string from gave you an array, not an object ie it looked something like: 您从JSON字符串获取的URL为您提供了一个数组,而不是一个对象,即它看起来像:

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

Note the brackets [ ] . 注意括号[ ] In that situation, your JSON parser gave you an NSArray as the top level (Objective-C) object. 在这种情况下,您的JSON解析器为您提供了一个NSArray作为顶级(Objective-C)对象。 You need some logic like: 你需要一些逻辑:

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.
}

What you have here is the results is not an NSDictionary but rather a NSArray. 你在这里得到的结果不是NSDictionary,而是NSArray。 NSArray doesn't have the allKeys selector causing the crash. NSArray没有导致崩溃的allKeys选择器。 If you'd post more info on the JSON Framework you are using, we could help source the issue better 如果您在正在使用的JSON框架上发布更多信息,我们可以帮助更好地解决问题

发布日志说这个调用[responseString JSONValue]返回NSArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM