Search code examples
iosobjective-cjsonnsarray

Mapping JSON response field into NSArray


Response:

{"rsBody": [{"productId":11, "productImageUrl":"http:xxxx"}, {"productId":9, "productImageUrl":"http:"xxxx"}]}

I know this is a repeated question, but still asking cause not getting the right way to do it. I am getting some response from php server as JSON in an array which consists two objects. I want to map the element of both objects productImageUrl in an NSArray. Resultant array should be somewhat like

NSArray =[{@"url":"productImageUrl1"},{@"url":@"ProductImageUrl2"}, nil];

productImageUrl1 = element of 1st object, productImageUrl2 = element of 2nd object.

I am parsing the response and able to to extract it from rsBody.

NSDictionary* response=(NSDictionary*)[NSJSONSerialization     
JSONObjectWithData:receivedData options:kNilOptions error:&tempError];

NSArray *rsBody = [response objectForKey:@"rsBody"];

Solution

  • Try this:

    NSMutableArray *arr = [[NSMutableArray alloc] init];
    
    NSDictionary* response = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
    
    NSArray *rsBody = [response objectForKey:@"rsBody"];
    
    for (NSDictionary *dict in rsBody)
    {
        NSMutableDictionary *dictURL = [[NSMutableDictionary alloc] init];
        [dictURL setValue:[dict valueForKey:@"productImageUrl"] forKey:@"url"];
        [arr addObject:dictURL];
    }
    
    NSLog(@"%@", arr);