How to remove White spaces in JSON String in Objective-c - ios

I am converting my json string to NSMutableDictionary by using below code,it's working fine,but if there is any unwanted white spaces are there then dictionary become null,i tested it with JSON lint, JSON parser, if i remove manually that white space that JSON string become valid, there is any method to remove that white spaces in JSON String.
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);
Thanks In Advance

Ok, so if you're certain that you need to do it yourself, here is a way to do it:
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
P.S. This is a slightly modified version of this answer (the author deserves an upvote IMHO): https://stackoverflow.com/a/1427224/2799410

Try this:
NSString *newString= [jsonString stringByReplacingOccurrencesOfString:#" "
withString:#""];
Now the newString will not have any white spaces.

Related

How to replace \n with comma and remove the last \n ? - iOS Objective C

I want to display text which return from server in a label. Server return something like this *English\nMalay\nTamil\n*.
Currently I use:
stringByReplacingOccurrencesOfString:#"\n" withString:#", "
to replace the \n with comma. But how do I remove the last \n?
Now my text in the label shows:
"English, Malay, Tamil,"
I would like to get like
"English, Malay, Tamil"
Try like this way.
NSString *string = #"English\nMalay\nTamil\n";
//Make array from string
NSMutableArray *array = [NSMutableArray arrayWithArray:[string componentsSeparatedByString:#"\n"]];
//Remove all empty object from array
[array removeObject:#""];
//Join array object and make string
NSString *newString = [array componentsJoinedByString:#", "];
NSLog(#"%#",newString);
Why not remove last \n before making replacement by using substringToIndex?
NSString *mString = #"English\nMalay\nTamil\n";
NSLog(#"mString===before===%#", mString);
mString = [mString substringToIndex:mString.length-1];
mString = [mString stringByReplacingOccurrencesOfString:#"\n" withString:#", "];
NSLog(#"mString===after===%#", mString);
Output
mString===before===English
Malay
Tamil
mString===after===English, Malay, Tamil
You can do this by using below code
NSString *string=#"English\nMalay\nTamil\n";
NSMutableArray *arryLanguagge = [[string componentsSeparatedByString: #"\n"] mutableCopy];
[arryLanguagge removeObject:#""];
NSString *strLanguaage=[arryLanguagge componentsJoinedByString:#","];
NSLog(#"%#",strLanguaage);

how to remove the \ character

I have a string with the following information:
\"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]\"
and I need to delete the character \ I'm trying to remove as follows, but the character is using the system and leaves close the line of code
NSString *filtered = [[[restConnection stringData] componentsSeparatedByString:#"\"] componentsJoinedByString:#""];
NSLog(#"filtrado: %#", filtered);
the error is
Expected ']' in this part : componentsSeparatedByString:#"\"]
Its looks like JSON data, instead interfering into JSON, just convert JSON string to NSData and then into NSDictionary or NSArray
NSString *jsonString = #"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *array = [NSArray arrayWithArray:json];
Now if you do following NSLog statement
NSLog(#"%#",[[json firstObject] objectForKey:#"CodRTA"]);
Result would be another NSDictionary.
{
CodRTA = 1;
MenssRTA = messaje error;
Resp = "";
}
Btw, I formatted your JSON response, its look like this,
Someting like that
string = [string stringByReplacingOccurrencesOfString:#"\\" withString:#""];
use this code
NSString *str=#"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]";
NSString *filtered = [[str componentsSeparatedByString:#"\\"] componentsJoinedByString:#""];
NSLog(#"filtrado: %#", filtered);

how to convert NSString to NSArray [duplicate]

This question already has answers here:
Comma-separated string to NSArray in Objective-C
(2 answers)
Closed 8 years ago.
I have a string like
NSString* str = #"[90, 5, 6]";
I need to convert it to an array like
NSArray * numbers = [90, 5 , 6];
I did a quite long way like this:
+ (NSArray*) stringToArray:(NSString*)str
{
NSString *sep = #"[,";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *temp=[str componentsSeparatedByCharactersInSet:set];
NSMutableArray* numbers = [[NSMutableArray alloc] init];
for (NSString* s in temp) {
NSNumber *n = [NSNumber numberWithInteger:[s integerValue]];
[numbers addObject:n];
}
return numbers;
}
Is there any neat and quick way to do such conversion?
Thanks
First remove the unwanted characters from the string, like white spaces and braces:
NSString* str = #"[90, 5, 6]";
NSCharacterSet* characterSet = [[NSCharacterSet
characterSetWithCharactersInString:#"0123456789,"] invertedSet];
NSString* newString = [[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""];
You will have a string like this: 90,5,6. Then simply split using the comma and convert to NSNumber:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:#","];
NSMutableArray* arrayOfNumbers = [NSMutableArray arrayWithCapacity:arrayOfStrings.count];
for (NSString* string in arrayOfStrings) {
[arrayOfNumbers addObject:[NSDecimalNumber decimalNumberWithString:string]];
}
Using the NSString category from this response it can be simplified to:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:#","];
NSArray* arrayOfNumbers = [arrayOfStrings valueForKey: #"decimalNumberValue"];
NSString* str = #"[90, 5, 6]";
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"[] "];
NSArray *array = [[[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""]
componentsSeparatedByString:#","];
Try like this
NSArray *arr = [string componentsSeparatedByString:#","];
NSString *newSTR = [str stringByReplacingOccurrencesOfString:#"[" withString:#""];
newSTR = [newSTR stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray *items = [newSTR componentsSeparatedByString:#","];
You can achieve that using regular expression 
([0-9]+)
NSError* error = nil;
NSString* str = #"[90, 5, 6]";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"([0-9]+)" options:0 error:&error];
NSArray* matches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];
Then you have a NSArray of string, you just need to iterate it and convert the strings to number and insert them into an array.

iOS: JSON displays dictionary out of order. How to present a reordering?

Say we have the following dictionary:
dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:currentItem], #"item number",
[NSNumber numberWithInt:([[item valueForKey:#"section"] intValue]+1)], #"section number",
currentDate, #"date of item",
[NSNumber numberWithDouble:timeDifference], #"time difference in millis",
nil];
Then I get the following output:
{
"time difference in millis" : 5.220093071460724,
"section number" : 1,
"date of item" : "28/04/2014 15:56:54,234",
"item number" : 3
}
I use the following code to convert the dictionary to JSON:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\\" withString:#""];
How can I manipulate the order in which the JSON string shows its keys. For example, I would like to have:
{
"item number" : 3,
"section number" : 1,
"date of item" : "28/04/2014 15:56:54,234",
"time difference in millis" : 5.220093071460724
}
or something else. The point is that I want control over this process. How do I get it? My first thought was writing a parser that shows the ordering in the way that I want.
Here are similar questions, but my emphasis is on manipulating the order instead of just recreating the order in which I put it from the dictionary.
JSON format: getting output in the correct order
Need JSON document that is generated to be in same order as objects inserted in NSMutableDictionary in iOS
NSDictionary is not ordered by definition.
Easiest will be to wrap everything into NSArray if you want to have same order.
To restate the question: how to take an inherently unordered input, produce a string who's specification is inherently unordered, but control the ordering of that string.
Reformatting the dictionary as an array would let you control input ordering, but produce a different output format.
The only reason I can imagine wanting to do this is if wish to use the JSON string not as JSON, but just as a string. The question can then be restated as just lexically reformatting the string.
How general purpose must it be? Can we assume that the JSON has simple, scalar values? Then...
- (NSString *)reorderJSON:(NSString *)json keys:(NSArray *)orderedKeys {
NSArray *splitJson = [json componentsSeparatedByString:#","];
NSMutableArray *splitResult = [NSMutableArray array];
for (NSString *key in orderedKeys) {
for (NSString *splitPair in splitJson) {
if ([self jsonPair:splitPair hasKey:key]) {
NSString *trimmedSplitPair = [splitPair stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"{}"]];
[splitResult addObject:trimmedSplitPair];
}
}
}
NSString *joinedResult = [splitResult componentsJoinedByString:#","];
return [NSString stringWithFormat:#"{%#\n}", joinedResult];
}
- (BOOL)jsonPair:(NSString *)pair hasKey:(NSString *)key {
// pair should begin with double quote delimited key
NSString *trimmedPair = [pair stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *splitPair = [trimmedPair componentsSeparatedByString:#"\""];
return [splitPair[1] isEqualToString:key];
}
Call it like this:
- (void)testJson {
NSDictionary *d = #{ #"time difference in millis": #5.220093071460724,
#"section number": #1,
#"date of item" : #"28/04/2014 15:56:54,234",
#"item number": #3};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSArray *orderedKeys = #[ #"item number", #"section number", #"date of item", #"time difference in millis"];
NSString *result = [self reorderJSON:jsonString keys:orderedKeys];
NSLog(#"%#", result);
}
You shouldn't want that. Dictionaries have no order and writing some code that uses the order will just lead to problems in the future.
That said, if you want to, you can write your own code to generate the JSON string from your (ordered) array of keys and dictionary of values.

Filter new line from array of email strings

I'm trying to send emails to a list that I get from a server which is an array of emails whose output is in this format
(
"john#gmail.com\n",
"katebell#gmail.com\n"
"\nakhil#gmail.com",
"mary#gmail.com",
"timcorb\n#gmail.com
)
Now as you can see some emails have newline characters in between and those emails doesnt get sent. I'm trying to find an efficient way to filter out those newlines, my current approach is to loop through all emails and check for newline in each email and if newline exist replace it with a null string. Is there a better way to do this or should I just stick with that? Also Will my current approach cause any issues in any other scenarios?
One way you can try using NSRegularExpression like this below :-
NSArray *array=#[#"john#gmail.com\n",#"katebell#gmail.com\n",#"\nakhil#gmail.com",#"mary#gmail.com",#"timcorb\n#gmail.com"];
NSString *string =[array componentsJoinedByString: #","];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\n" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
NSLog(#"%#",modifiedString);
Output:-
john#gmail.com,katebell#gmail.com,akhil#gmail.com,mary#gmail.com,timcorb#gmail.com
try something like this
NSString *fileName = #"\ntest\n";
fileName = [fileName stringByReplacingOccurrencesOfString:#"\n" withString:#""];
eg.
NSString * str = #"timcorb\n#gmail.com";
str = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSLog(#"%#",str);
it will Log 2014-01-10 01:01:00.256 demo[26220] timcorb#gmail.com
You can use the below code for replacing characters in a string.
NSString *email = #"\nakhi\nl#gmail.com";
NSString *actualEmail = [email stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSMutableArray* emailArray = [[NSMutableArray alloc] init];
for (int _index = 0; _index < [yourArray count]; _index++) {
[emailArray addobject:[[yourArray objectAtIndex:_index] stringByReplacingOccurrencesOfString:#"\n" withString:#""]];
}
This will give you your email array

Resources