本文介绍了Objective-C - 如何将NSString转换为转义的JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以包含引号的NSString,\,/,\r,\\\
,我想将其转换为JSON编码的字符串,因此这样的字符串

成为

是有现在的功能让我这样做吗?



此外,我在我的项目中使用SBJson,但是找不到SBJson是否可以执行此操作。



NSJSONSerialization不在桌面上,因为我的应用程序仍然需要支持OSX 10.6

解决方案

这是否回答你的问题? >

   - (NSString *)JSONString :( NSString *)aString {
NSMutableString * s = [NSMutableString stringWithString:aString];
[s replaceOccurrencesOfString:@\withString:@\\\选项:NSCaseInsensitiveSearch范围:NSMakeRange(0,[s length])];
[s replaceOccurrencesOfString:@/withString:@\\ /options:NSCaseInsensitiveSearch range:NSMakeRange(0,[s length])];
[s replaceOccurrencesOfString:@\\\
withString:@\\\\
选项:NSCaseInsensitiveSearch范围:NSMakeRange(0,[s length])];
[s replaceOccurrencesOfString:@\bwithString:@\\b选项:NSCaseInsensitiveSearch范围:NSMakeRange(0,[s length])];
[s replaceOccurrencesOfString:@\fwithString:@\\f选项:NSCaseInsensitiveSearch范围:NSMakeRange(0,[s length])];
[s replaceOccurrencesOfString:@\rwithString:@\\r选项:NSCaseInsensitiveSearch范围:NSMakeRange(0,[s length])];
[s replaceOccurrencesOfString:@\twithString:@\\t选项:NSCaseInsensitiveSearch范围:NSMakeRange(0,[s length])];
return [NSString stringWithString:s];
}

资料来源:


I have a NSString that may contain quotes,\, /, \r, \n, and I want to convert it to a JSON encoded string so strings like this

becomes

Is there a existing function to let me do this?

Also, I am using SBJson in my project but I cannot find whether SBJson can do this or not.

NSJSONSerialization is not on the table since my application still needs to support OSX 10.6

解决方案

Does this answer your question?

-(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];
}

Source: converting NSString to JSON string

这篇关于Objective-C - 如何将NSString转换为转义的JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 20:06