iOS 处理导致JSON解析失败的特殊字符

在网络请求完成后会获得NSData类型的数据,通常情况下直接使用+ ( id)JSONObjectWithData:options: error:方法转换即可,但实际开发数据中会包含一些特殊字符导致解析失败。

目前找到导致JSON解析失败的字符串如下:

\ \’ \n \r \t \\ \f \b \v

方法一:删除特殊字符

1
2
3
4
5
6
7
8
9
10
11
12
NSString *jsonStr = @"{\"code\":\"0\",\"data\":{\"content\":\"1、\' 2、\r\n 3、\n 4、\r 5、\t 6、\\ 7、\f 8、\b 9、\v \"},\"message\":\"操作成功\"}";
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\'" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\f" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\b" withString:@""];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\v" withString:@""];
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

方法二:使用 \ 进行转译处理

1
2
3
4
5
6
7
8
9
10
11
NSString *jsonStr = @"{\"code\":\"0\",\"data\":{\"content\":\"1、\' 2、\r\n 3、\n 4、\r 5、\t 6、\\ 7、\f 8、\b 9、\v \"},\"message\":\"操作成功\"}";
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\')" withString:@"\\\\'" options:NSRegularExpressionSearch range:NSMakeRange(0, jsonStr.length)];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\n)" withString:@"\\\\n" options:NSRegularExpressionSearch range:NSMakeRange(0, jsonStr.length)];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\r)" withString:@"\\\\r" options:NSRegularExpressionSearch range:NSMakeRange(0, jsonStr.length)];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\t)" withString:@"\\\\t" options:NSRegularExpressionSearch range:NSMakeRange(0, jsonStr.length)];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\f)" withString:@"\\\\f" options:NSRegularExpressionSearch range:NSMakeRange(0, jsonStr.length)];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\b)" withString:@"\\\\b" options:NSRegularExpressionSearch range:NSMakeRange(0, jsonStr.length)];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\v)" withString:@"\\\\v" options:NSRegularExpressionSearch range:NSMakeRange(0, jsonStr.length)];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\\\\)" withString:@"\\\\\\\\" options:NSRegularExpressionSearch range:NSMakeRange(0, jsonStr.length)];
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

总结

直接删除特殊字符相对来说比较暴力,推荐使用\进行转译处理特殊字符串