user2543991
user2543991

Reputation: 625

How to parse NSDictionary of unnamed arrays

Here is the NSLog result of a dictionary, dict:

  (
     {
         namelists = {
                        watchlist = (a, b, c, ... )
                     }
     },

     {
         namelists = {
                        watchlist = (x, y, z, ... )
                     }
     }
   )

How can I get the watchlist array? When I tried this:

  NSAarray *array = dict[@"nameLists"][@"watchlist"]

I get error: "unrecognized selector sent to instance". I think that the unnamed array is not referred here. How can I get the watchlist array? Thanks in advance.

Upvotes: 0

Views: 587

Answers (2)

SPA
SPA

Reputation: 1289

this data structure can be coded like this

NSArray *arrayOfNamelists = @[@{@"namelists" : @{@"watchlist" : @[@"a",@"b",@"c"]}},
                              @{@"namelists" : @{@"watchlist" : @[@"x",@"y",@"z"]}}];

and an element in the array of strings can be accessed like this

NSString *entry = [[arrayOfNamelists[1] objectForKey:@"namelists"]
                   objectForKey:@"watchlist"][2];

which in this example gives 'z'

To check this

NSLog(@"%@\ncount = %i",arrayOfNamelists,arrayOfNamelists.count);

for(NSDictionary *namelistDictionary in arrayOfNamelists){
    NSDictionary *watchlistDictionary = [namelistDictionary objectForKey:@"namelists"];
    NSArray *watchlistsArray = [watchlistDictionary objectForKey:@"watchlist"];
    for(NSString *watchlistEntry in watchlistsArray){
        NSLog(@"%@",watchlistEntry);
    }
};

gives

(
    {
    namelists =         {
        watchlist =             (
            a,
            b,
            c
        );
    };
},
    {
    namelists =         {
        watchlist =             (
            x,
            y,
            z
        );
    };
}

)

count = 2

a

b

c

x

y

z

Upvotes: 1

Rob
Rob

Reputation: 437632

You're under the impression that you're dealing with a dictionary. But that's an array of dictionaries. So you want:

NSArray *jsonObject = ... // get that main object however you want, presumably NSJSONSerialization
NSArray *watchlist = jsonObject[0][@"namelists"][@"watchlist"]

or

for (NSDictionary *dict in jsonObject)
{
    NSArray *watchlist = dict[@"namelists"][@"watchlist"];

    // now do something with watchlist
}

Upvotes: 3

Related Questions