3

I am converting the response data from a web request to an NSString in the following manner:

NSData *data = self.responseData;
if (!data) {
    return nil;
}
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)[self.response textEncodingName]));
NSString *responseString = [[NSString alloc] initWithData:data encoding:encoding];

However the resulting string looks like this:

"birthday":"04\/01\/1990",
"email":"some.address\u0040some.domain.com"

What I would like is

"birthday":"04/01/1990",
"email":"some.address@some.domain.com"

without the backslash escapes and unicode. What is the cleanest way to do this?

jcm
  • 1,781
  • 1
  • 15
  • 27
  • 1
    looks like the response is encoded in json format, then simply use a json decoder like SBJson to get the correct strings – Felix Jan 26 '12 at 13:10
  • @phix23 Didn't think of that, parsing the JSON does give the correct form! Write an answer and I'll accept it. – jcm Jan 26 '12 at 13:24

2 Answers2

1

You can replace (or remove) characters using NSString's stringByReplacingCharactersInRange:withString: or stringByReplacingOccurrencesOfString:withString:.

To remove (convert) unicode characters, use dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES (from this answer).

I'm sorry if the following has nothing to do with your case: Personally, I would ask myself where did that back-slashes come from in the first place. For example, for JSON, I'd know that some sort of JSON serializer on the other side escapes some characters (so the slashes are really there, in the response, and that is not a some weird bug in Cocoa). That way I'd able to tell for sure which characters I have to handle and how. Or maybe I'd use some kind of library to do that for me.

Community
  • 1
  • 1
zrslv
  • 1,748
  • 1
  • 14
  • 25
1

The response seems to be JSON-encoded. So simply decode the response string using a JSON library (SBJson, JsonKit etc.) to get the correct form.

Felix
  • 35,354
  • 13
  • 96
  • 143