Objective-C - How to convert NSString to escaped JSON string?

lakeskysea picture lakeskysea · Apr 5, 2013 · Viewed 12.2k times · Source

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

"text1\text2"

becomes

\"text1\\text2\"

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

Answer

Jean picture Jean · Apr 5, 2013

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:@"/" 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