2015-12-31 114 views
0

這裏是我的聯繫人的手機號碼和姓名轉換的NSString數據轉換成JSON格式

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格式的響應。

+0

爲什麼你想將它轉換爲JSON?這只是一次性轉換嗎?或者你會定期這樣做嗎?如果前者,您可以在文本編輯器(如Notepad ++)中使用正則表達式。在後一種情況下,我會寫一個小程序來做到這一點。如果您正在解析來自Web服務的這些結果,那麼您需要採取幾個字符串處理步驟來獲取所需的JSON。 – mikeyq6

+0

橡樹我想把這個結果傳遞給一個web服務然後步驟 –

回答

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 [email protected]"]}"]; 
    output = result; 
} 

上面做了一些假設,(1)該輸入的格式將總是意味着該電話號碼是在每行完全相同的位置, (2)格式總是意味着電話號碼只在奇數行上。

如果您需要將數字解析爲某種格式,則可以在將其附加到結果字符串之前添加另一個函數來格式化數字。

0

這裏是我的假設(回答提問時它不應該是必要作任何假設):

  1. 初始數據被包含在與NAME1,數字1,NAME2 NUMBER2等
  2. 陣列
  3. 您想提取數字並將它們放入字典中,「聯繫人」作爲關鍵字,值作爲數字數組。
  4. 您想將字典格式化爲JSON以便在某處發送。

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]); 
} 
+0

仍然沒有得到 –