Give this a go. Added the necessary code to create the JSON on top of your code. If there are no phone numbers or emails for a contact, NSNull is added for that key. Make sure to check for it when you are pulling the data out of the JSON. Didn't build the code, so let me know if you run into any errors.
NSMutableArray *usersArray = [[NSMutableArray alloc] init];
NSMutableDictionary *singleUserDictionary = [[NSMutableDictionary alloc] init];
NSMutableArray *phoneNumbersArray = [[NSMutableArray alloc] init];
NSMutableArray *emailArray = [[NSMutableArray alloc] init];
for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
ABRecordRef person = CFArrayGetValueAtIndex(people, i);
////get full name////
NSString *fullname = @"";
if (ABRecordCopyValue(person, kABPersonFirstNameProperty)!=NULL){
fullname = [NSString stringWithFormat:@"%@ ", ABRecordCopyValue(person, kABPersonFirstNameProperty)];
}
if (ABRecordCopyValue(person, kABPersonMiddleNameProperty)!=NULL){
fullname = [NSString stringWithFormat:@"%@%@ ", fullname,ABRecordCopyValue(person, kABPersonMiddleNameProperty)];
}
if (ABRecordCopyValue(person, kABPersonLastNameProperty)!=NULL){
fullname = [NSString stringWithFormat:@"%@%@", fullname,ABRecordCopyValue(person, kABPersonLastNameProperty)];
}
fullname = [fullname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"fullname: %@",fullname);
[singleUserDictionary setObject:fullname forKey:@"name"];
////get phone numbers////
ABMultiValueRef phonenumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
if (ABMultiValueGetCount(phonenumbers)>0)
{
for (CFIndex j=0; j < ABMultiValueGetCount(phonenumbers); j++)
{
NSString *phonenumber = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phonenumbers, j));
NSLog(@"phone number: %@",phonenumber);
[phoneNumbersArray addObject:phonenumber];
}
}
else
[phoneNumbersArray addObject:[NSNull null]];
[singleUserDictionary setObject:phoneNumbersArray forKey:@"phone_numbers"];
CFRelease(phonenumbers);
////get emails////
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
if (ABMultiValueGetCount(emails)>0)
{
for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++)
{
NSString *email = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(emails, j));
NSLog(@"email: %@",email);
[emailArray addObject:email];
}
}
else
[emailArray addObject:[NSNull null]];
[singleUserDictionary setObject:emailArray forKey:@"email_addresses"];
CFRelease(emails);
[usersArray addObject:[NSDictionary dictionaryWithDictionary:singleUserDictionary]];
[singleUserDictionary removeAllObjects];
[phoneNumbersArray removeAllObjects];
[emailArray removeAllObjects];
}
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:usersArray options:0 error:&error];
if (error) {
//json success
}
CFRelease(addressBook);
CFRelease(people);