关闭

NSString 转化成 JSON 字符串

251人阅读 评论(0) 收藏 举报
分类:
I needed a quick way to encode an NSString to be used in a JSON object in an iPhone project. There are libraries to do this like TouchJSON, but I didn’t want to link a whole library to insert a string into a Facebook query.

A JSON string looks like this (image from json.org):



NSString is already UTF-8, but characters like \n have to be escaped. Here’s the method I came up with:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:295438次
    • 积分:7471
    • 等级:
    • 排名:第3009名
    • 原创:471篇
    • 转载:68篇
    • 译文:2篇
    • 评论:27条
    最新评论