iPhone NSArray from Dictionary of Dictionary values iPhone NSArray from Dictionary of Dictionary values json json

iPhone NSArray from Dictionary of Dictionary values


First off, since you're using JSON, I'm hoping you've already found BSJSONAdditions and/or json-framework, both of them open-source projects for parsing JSON into native Cocoa structures for you. This blog post gives an idea of how to use the latter to get an NSDictionary from a JSON string.

The problem then becomes one of finding the matching values in the dictionary. I'm not aware of a single method that does what you're looking for — the Cocoa frameworks are quite powerful, but are designed to be very generic and flexible. However, it shouldn't be too hard to put together in not too many lines... (Since you're programming on iPhone, I'll use fast enumeration to make the code cleaner.)

NSDictionary* jsonDictionary = ...NSDictionary* innerDictionary;NSArray* requiredIDs = ...NSMutableDictionary* matches = [NSMutableDictionary dictionary];for (id key in jsonDictionary) {    innerDictionary = [jsonDictionary objectForKey:key];    if ([requiredIDs containsObject:[innerDictionary objectForKey:@"id"]])        [matches setObject:[innerDictionary objectForKey:@"name"]                    forKey:[innerDictionary objectForKey:@"id"]];}

This code may have typos, but the concepts should be sound. Also note that the call to [NSMutableDictionary dictionary] will return an autoreleased object.


Have you tried this NSDictionary method:

+ (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys