JSON是不能解析带有换行符字符串的,今天被这傻问题碰到了,服务器获取的json字符串数据有换行符,怎么转json都是null。。。
而且有些不能直接用stringByReplacingOccurrencesOfString就能替换。还是用NSScanner好用
+(NSString *)ReplacingNewLineAndWhitespaceCharactersFromJson:(NSString *)dataStr{
NSScanner *scanner = [[NSScanner alloc] initWithString:dataStr];
[scanner setCharactersToBeSkipped:nil];
NSMutableString *result = [[NSMutableString alloc] init];
NSString *temp;
NSCharacterSet*newLineAndWhitespaceCharacters = [ NSCharacterSet newlineCharacterSet];
// 扫描
while (![scanner isAtEnd])
{
temp = nil;
[scanner scanUpToCharactersFromSet:newLineAndWhitespaceCharacters intoString:&temp];
if (temp) [result appendString:temp];
// 替换换行符
if ([scanner scanCharactersFromSet:newLineAndWhitespaceCharacters intoString:NULL]) {
if (result.length > 0 && ![scanner isAtEnd]) // Dont append space to beginning or end of result
[result appendString:@"|"];
}
}
return result;
}