jcm
jcm

Reputation: 1789

Removing unicode and backslash escapes from NSString converted from NSData

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":"[email protected]"

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

Upvotes: 3

Views: 6623

Answers (2)

Felix
Felix

Reputation: 35394

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.

Upvotes: 1

zrslv
zrslv

Reputation: 1846

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.

Upvotes: 1

Related Questions