iOS,使用 ABAddressBookCreate 的元素创建 JSON 对象

标签 ios objective-c json nsdictionary nsjsonserialization

我正在使用 ABAddressBookCreateWithOptionsABAddressBookCopyArrayOfAllPeople 来获取所有联系人的信息。

我可以这样得到人的全名、电子邮件和电话号码:

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"]}]

场景:如果人有电子邮件地址,则将其添加到 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。如果联系人没有电话号码或电子邮件,则为该键添加 NSNull。当您从 JSON 中提取数据时,请务必检查它。没有构建代码,所以如果您遇到任何错误,请告诉我。

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);

关于iOS,使用 ABAddressBookCreate 的元素创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22976972/

相关文章:

ios - 自定义单元格图像作为 Swift 中的附件类型

objective-c - 为什么静态库有一个带有 init 方法的类?

json - 尝试将 json 解析为类对象失败

json - 使用 Postman 客户端获取 Twitter 时间线 (JSON)

ios - 键盘扩展内存泄漏?

iphone - iOS 崩溃并出现 EXC_BAD_ACCESS(code=1)

ios - Apple ios API - 电话

objective-c - 关闭通过模态 segue 显示的 View

objective-c - 在重写的类方法中调用 super

javascript - 带有自定义 json 数据的 JsTree