iOS 字符串处理 -- 删除h5样式

后台返回了

result--{
 messages = "";
result = "{\"address\":\"\U9e93\U8c37\U4f01\U4e1a\U5e7f\U573ac1\U680b103\",\"articleId\":1388,\"articleNumber\":1,\"contacts\":\"\U674e\U5c0f\U59d0\",\"contactsPhone\":\"18207325127\",\"content\":\"

这种恶心的数据,这是转过一次了的数据,有时候我使用以下方式再转一次就可以解决:

NSString *str = result[@"result"];
            NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

但是 有时候莫名其妙的又崩溃了,后来找了很久,加了一个去掉不规则字符的方法 removeUnescapedCharacter:

 NSString *str = result[@"result"];
            str = [NSString removeUnescapedCharacter:str];
            NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

具体的就是,我是直接就加在了 NSString 的方法里的:

+(NSString *)removeUnescapedCharacter:(NSString *)inputStr
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];//获取那些特殊字符
    NSRange range = [inputStr rangeOfCharacterFromSet:controlChars];//寻找字符串中有没有这些特殊字符
    if (range.location != NSNotFound)
    {
        NSMutableString *mutable = [NSMutableString stringWithString:inputStr];
        while (range.location != NSNotFound)
        {
            [mutable deleteCharactersInRange:range];//去掉这些特殊字符
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputStr;
}

PS: 建议后台处理好。。

你可能感兴趣的:(iOS 字符串处理 -- 删除h5样式)