开发者

Keys in a dictionary from JSON

I'm importing a JSON dictionary. 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'

Why is allKey开发者_如何学JAVAs not working?

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


The URL that you obtained that JSON string from gave you an array, not an object i.e. it looked something like:

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

Note the brackets [ ]. In that situation, your JSON parser gave you an NSArray as the top level (Objective-C) object. 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. NSArray doesn't have the allKeys selector causing the crash. If you'd post more info on the JSON Framework you are using, we could help source the issue better


Posted log says that this call [responseString JSONValue] returns NSArray.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜