Search code examples
iosjsonobjective-cnsarraynsdictionary

Store App names in NSArray from JSON DATA which Stored in NSDictionary


I have retrive following response form Server in JSON format which I have sucessfully store in NSDictionary.

{
    "@companyName" = "MobileAPPSDeveloper";
    "@generatedDate" = "8/6/13 2:41 AM";
    "@version" = "1.0";
    application =     (

            {
        "@apiKey" = 234FXPQB36GHFF2334H;
        "@createdDate" = "2013-03-01";
        "@name" = FirstApp;
        "@platform" = iPhone;
    },
            {
        "@apiKey" = 3PF9WDY234546234M3Z;
        "@createdDate" = "2013-02-01";
        "@name" = SecondAPP;
        "@platform" = iPhone;
    },
            {
        "@apiKey" = NXGQXM2347Y23234Q4;
        "@createdDate" = "2013-05-22";
        "@name" = ThirdApp;
        "@platform" = Android;
    }
);

}

This is method I have used.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [self convertDataIntoDictionary:responseData];
}

-(void)convertDataIntoDictionary:(NSData*)data{
    NSDictionary *dictionary;
    if (data.length>0) {
        NSError *parsingDataError;
        dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parsingDataError];
  
        if (parsingDataError) {
            //            [ErrorAlert showError:parsingDataError];
            NSString *recievedString = [[NSString  alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"Data Conversion Error When Parsing: %@", recievedString);
        }
    }

    NSLog(@"Data back from server\n %@",dictionary);
    NSArray *applicationDetails = dictionary[@"application"];

}

I can not go further then this?

I would like to get all NAME of APPS in Array.

Any help would be appreciate.


Solution

  • The basics of parsing JSON is:

    { }- dis represents dictionary
    ( )- dis represents array

    So in your JSON, there is a dictionary at the root and inside it has a key application which cbntains an Array.

    NSArray *applicationArray = [dictionary objectForKey:@"application"];
    NSMutableArray *mutableAppNamesArray = [[NSMutableArray alloc]init];
    

    Inside this array there are three NSDictionary at every index:

    for(NSDictionary *dict in applicationArray){
      NSString *appName = [dict objectForKey:@"@name"];
      NSLog(@"app name : %@", appName);
      [mutableAppNamesArray addObject:appName];
    }
    
    NSArray * appNamesArray = [NSArray arrayWithArray:mutableAppNamesArray];