2015-09-30 77 views
0

我正在通過使用下面的代碼將我的json字符串轉換爲NSMutableDictionary,它工作正常,但是如果有任何不需要的空格,那麼字典將變爲空,我測試它與JSON lint,JSON解析器,如果我手動刪除JSON字符串變爲有效的空白空間,則有任何方法可以刪除JSON字符串中的空白。如何刪除JSON字符串中的空白Objective-c

NSMutableDictionary *responseDictionary; 
     NSData * data = (NSData *)responseObject; 
     NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 
     responseDictionary = [NSJSONSerialization JSONObjectWithData:data 
                   options:NSJSONReadingMutableContainers 
                   error:nil]; 
     NSLog(@"the value in the dic is%@",responseDictionary); 

在此先感謝

+4

聽起來像它需要在生成JSON的軟件中修復。 – Droppy

+0

請參閱此鏈接:http://stackoverflow.com/questions/8075147/replace-all-nsnull-objects-in-an-nsdictionary –

+0

可能重複的[白色空間序列的單個字符](http:///stackoverflow.com/questions/758212/collapse-sequences-of-white-space-into-a-single-character) –

回答

1

好了,如果你確信你需要自己做,這裏是一個辦法做到這一點:

NSString *theString = @" Hello  this is a long  string! "; 

NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet]; 
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"]; 

NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces]; 
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings]; 
theString = [filteredArray componentsJoinedByString:@""]; // using empty string to concatenate the strings 

附:這是這個答案的一個稍作修改的版本(筆者對得起給予好評恕我直言):https://stackoverflow.com/a/1427224/2799410

0

試試這個:

NSString *newString= [jsonString stringByReplacingOccurrencesOfString:@" " 
                  withString:@""]; 

現在newString不會有任何空格。

+0

PO不僅要刪除單個空格,還要刪除空白家族中所有出現的字符(例如換行符,空格,製表符等)。 –

+0

所以你可以試試這個:
NSString * string = @「Hello,World!」; NSCharacterSet * separator = [NSCharacterSet whitespaceAndNewlineCharacterSet]; NSArray * stringComponents = [string componentsSeparatedByCharactersInSet:separator]; –

+0

這正是我在這裏提出的:http://stackoverflow.com/a/32861064/2799410 –

相關問題