lak*_*sea 4 escaping objective-c sbjson
我有一个可能包含引号的NSString,\,/,\ r,\n,我想将它转换为JSON编码的字符串,所以像这样的字符串
"文本1 \文本2"
变
\ "文本1 \\文本2 \"
是否有现成的功能让我这样做?
此外,我在我的项目中使用SBJson但我无法找到SBJson是否可以这样做.
NSJSONSerialization不在桌面上,因为我的应用程序仍然需要支持OSX 10.6
Jea*_*ean 12
这回答了你的问题了吗?
-(NSString *)JSONString:(NSString *)aString {
NSMutableString *s = [NSMutableString stringWithString:aString];
[s replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
[s replaceOccurrencesOfString:@"/" withString:@"\\/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
[s replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
[s replaceOccurrencesOfString:@"\b" withString:@"\\b" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
[s replaceOccurrencesOfString:@"\f" withString:@"\\f" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
[s replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
[s replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
return [NSString stringWithString:s];
}
Run Code Online (Sandbox Code Playgroud)