Search code examples
iosjsonnsjsonserialization

Create JSON format in iOS


I have two send data to server in JSON format, below is the format which server needs

{
"employees": [
{ "firstName":"John" "middelName":"M" "lastName":"Doe" }, 
{ "firstName":"Anna" "middelName":"J" "lastName":"Smith" }, 
{ "firstName":"Peter" "middelName":"K" "lastName":"Jones" }
]
}

Now I have three NSMutableArrays , 1st array contains firstName, second array contains middleName and third array contains lastName,

If it was just a single record I could have created it this way

NSDictionary *dictionary = @{@"employees": @{@"firstName":"John" "middelName":"M" "lastName":"Doe"}};

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        NSLog(@"Error creating JSON object: %@", [error localizedDescription]);
    }

Now I am getting confused on how to create an array of records


Solution

  • Try something like this:

    /* assuming the arrays have equal length, no error checking */
    NSMutableArray * employees = [NSMutableArray new];
    NSUInteger idx = 0;
    for(NSString * firstName in firstNames) {
        [employees addObject:@{
            @"firstName":firstName,
            @"middleName":[middleNames objectAtIndex:idx],
            @"lastName":[lastNames objectAtIndex:idx]
        }];
        idx++;
    }
    id sendThis = @{@"employees": employees};
    /* do your JSON stuff with sendThis */