【发布时间】:2014-04-10 01:23:47
【问题描述】:
我正在使用 ABAddressBookCreateWithOptions 和 ABAddressBookCopyArrayOfAllPeople 来获取所有联系人的信息。
我可以得到这样的人的全名、电子邮件和电话号码:
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
people = ABAddressBookCopyArrayOfAllPeople(addressBook);
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);
////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);
}
}
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);
}
}
CFRelease(emails);
}
CFRelease(addressBook);
CFRelease(people);
一切都很完美。但我需要使用以下信息创建一个 JSON 对象:
[{"name":"Christine Work","phone_numbers":["+99023424234"]},{"name":"Alex Bla","phone_numbers":["+135352125262","+13433452347"],"email_addresses":["bla@bla.com","bla2@bla2.com"]}]
场景:如果人有email地址,则将其添加到json对象中,如果没有,则不包含在json中。
如果一个人有多个电话号码或多个电子邮件地址,则将它们全部添加到 json。
我被困在这里了。我知道如何使用 NSDictionary 创建一个 json 对象:
NSError *error;
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
@"alex", @"name",
@"+90225252", @"phones",
nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:info encoding:NSUTF8StringEncoding];
但是如何在循环中将此代码集成到我的场景中。
【问题讨论】:
-
接收 JSON 的是什么?即使对象为零,您是否需要包含键,还是可以一起跳过它们?
-
JSON 的最外层是一个数组,因此您应该将其输入序列化程序。该数组包含多个字典,包括“name”、“phone_numbers”、“email_addresses”。 “phone_numbers”和“email_addresses”值又是数组。应该很容易构建该结构。
标签: ios objective-c json nsdictionary nsjsonserialization