humblePilgrim
humblePilgrim

Reputation: 1806

Replace " in string with \"

I am trying to send a string to the server. I encode it and set it as the body of an HTTP request using

[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

Where body is the string.It has to be in json format.

For example

body = [NSString stringWithFormat:@"{\"emailBody\":\"%@\"}",string] ;

should be valid

But i accept string from user and it may contain double quotes.Therefore i have to escape double quotes(") in it. For example if want to send just one "

{\"emailBody\":\"\\\"\"}

(harddcoded) returns positive response from server.

So i would like to create such a string from the original string.I tried the following

string = [string stringByReplacingOccurencesOfString:@"\"" withString:@"\\\\\""];

But it did not work.I got \" in my test email.Thats as far as i have been able to get.

Am I taking the right approach ??I would appreciate it if someone would point me in the right direction.Thanks

Upvotes: 0

Views: 102

Answers (1)

Cyrille
Cyrille

Reputation: 25144

You should generate your JSON directly from a dictionary. That'll take care of all the encoding automatically for you:

NSDictionary *body = @{@"emailBody": string};
NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];

if (!jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [request setHTTPBody:jsonString];
}

Upvotes: 2

Related Questions