简体   繁体   English

从NSData转换的NSString中删除unicode和反斜杠转义

[英]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: 我正在通过以下方式将响应数据从Web请求转换为NSString:

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. 没有反斜杠转义和unicode。 What is the cleanest way to do this? 最干净的方法是什么?

You can replace (or remove) characters using NSString's stringByReplacingCharactersInRange:withString: or stringByReplacingOccurrencesOfString:withString: . 您可以使用NSString的stringByReplacingCharactersInRange:withString:stringByReplacingOccurrencesOfString:withString:替换(或删除)字符。

To remove (convert) unicode characters, use dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES (from this answer ). 要删除(转换)unicode字符,请使用dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES (来自此答案 )。

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). 例如,对于JSON,我知道另一边的某种JSON序列化程序会逃避一些字符 (因此斜杠确实存在于响应中,并且这不是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. 或者也许我会使用某种类型的库为我做这件事。

The response seems to be JSON-encoded. 响应似乎是JSON编码的。 So simply decode the response string using a JSON library (SBJson, JsonKit etc.) to get the correct form. 因此,只需使用JSON库(SBJson,JsonKit等)解码响应字符串即可获得正确的表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM