Removing unicode and backslash escapes from NSString converted from NSData

£可爱£侵袭症+ 提交于 2019-12-31 01:49:18

问题


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?


回答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.




回答2:


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.



来源:https://stackoverflow.com/questions/9018347/removing-unicode-and-backslash-escapes-from-nsstring-converted-from-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!