将NSString数据转换为JSON格式

时间:2015-12-31 10:42:14

标签: ios json web-services nsdictionary contacts

以下是我对联系人手机号码和姓名的回复

2015-12-31 13:39:58.563 LCall[1448:53537] 888-555-1212
2015-12-31 13:39:58.563 LCall[1448:53537] John Appleseed
2015-12-31 13:39:58.564 LCall[1448:53537] (415) 555-3695
2015-12-31 13:39:58.565 LCall[1448:53537] Kate Bell
2015-12-31 13:39:58.565 LCall[1448:53537] 555-522-8243
2015-12-31 13:39:58.565 LCall[1448:53537] Anna Haro
2015-12-31 13:39:58.566 LCall[1448:53537] (408) 555-3514
2015-12-31 13:39:58.566 LCall[1448:53537] Daniel Higgins
2015-12-31 13:39:58.567 LCall[1448:53537] 555-610-6679
2015-12-31 13:39:58.567 LCall[1448:53537] David Taylor
2015-12-31 13:39:58.568 LCall[1448:53537] (707) 555-1854
2015-12-31 13:39:58.568 LCall[1448:53537] Hank Zakroff`

我想以下面的形式转换他们的手机号码

{"contacts":["+918146411786","8528840200"]}

或JSON格式。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方式:

-(void)parseResultsString:(NSString *)input into:(NSString *)output {
    int phoneNumberStartingIndex = 40;
    NSMutableString* result = @"{\"contacts\":[";

    NSCharacterSet *separator = [NSCharacterSet newlineCharacterSet];
    NSArray *rows = [input componentsSeparatedByCharactersInSet:separator];
    int counter = 0;
    NSString *comma = @"";

    for (NSString* line in rows) {
        if(counter % 2 == 0) { // Skip every 2nd line
            NSString *number = [line substringFromIndex:phoneNumberStartingIndex];
            [result appendFormat:@"%@\"%@\"", comma, number];
            comma = @",";
        }
    }
    [result appendString@"]}"];
    output = result;
}

以上做了一些假设,(1)输入的格式总是意味着电话号码在每一行的完全相同的位置,以及(2)格式总是意味着电话号码是只在奇数行上。

如果您需要将数字解析为某种格式,那么您可以添加另一个函数来格式化数字,然后再将其附加到结果字符串。

答案 1 :(得分:0)

以下是我的假设(在回答问题时不必做出任何假设):

  1. 初始数据包含在名为name1,number1,name2,number2等的数组中。
  2. 您想要提取数字并将它们放入字典中,其中“contacts”作为键,值作为数字数组。
  3. 您希望将字典格式化为JSON以便在某处发送。
  4. NSArray *namesAndNumbers = ...;
    NSAssert(([namesAndNumbers count] & 1) == 0, @"Input array has odd number of elements");
    NSMutableArray *numbers = [NSMutableArray new];
    for (NSUInteger i = 1; i < [namesAndNumbers count]; i += 2) {
        [numbers addObject:namesAndNumbers[i]];
    }
    NSDictionary *contacts = @{ @"contacts" : numbers };
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:containts
                                                       options:0
                                                         error:&error];
    if (jsonData) {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        // Do something with string
    } else {
        NSLog(@"Failed to format JSON: %@", [error localizedDescription]);
    }