Objective-C的 - 如何的NSString转换为逃脱JSON字符串?(Objective-

2019-08-19 23:29发布

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

“文本1 \文本2”

\ “文本1 \\文本2 \”

是否有一个现有的功能,让我做到这一点?

另外,我在我的项目中使用SBJson,但我找不到SBJson是否能做到这一点或没有。

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

Answer 1:

这回答了你的问题了吗?

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

来源: 转换的NSString JSON字符串



Answer 2:

让我们做更多的原生JSON的路;)

如果妳喜欢我的回答,请明星我在https://github.com/wanjochan

//trick: id(@[s]) => string => trim [] => target
//NSString *s
s=[[NSString alloc] initWithData:
  [NSJSONSerialization dataWithJSONObject:@[s] options:0 error:nil]
  encoding:NSUTF8StringEncoding];
s=[[s substringToIndex:([s length]-1)] substringFromIndex:1];


Answer 3:

斯威夫特2:

/// Escape reserved characters to produce a valid JSON String
/// For example double quotes `"` are replaced by `\"`
/// - parameters:
///   - String: an unescaped string
/// - returns: valid escaped JSON string
func JSONString(str: String?) -> String? {
    var result : String? = nil
    if let str = str {
        result = str
            .stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("/", withString: "\\/", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\n", withString: "\\n", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\u{8}", withString: "\\b", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\u{12}", withString: "\\f", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\r", withString: "\\r", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\t", withString: "\\t", options: .CaseInsensitiveSearch)
    }
    return result
}

斯威夫特3:

func JSONString(str: String) -> String {
    var result = str
    result = result.replacingOccurrences(of: "\"", with: "\\\"")
        .replacingOccurrences(of: "/", with: "\\/")
        .replacingOccurrences(of: "\n", with: "\\n")
        .replacingOccurrences(of: "\u{8}", with: "\\b")
        .replacingOccurrences(of: "\u{12}", with: "\\f")
        .replacingOccurrences(of: "\r", with: "\\r")
        .replacingOccurrences(of: "\t", with: "\\t")

    return result
}

非常有用的,以防止错误: Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence around character 123."



Answer 4:

斯威夫特4解决方案

extension String {
    var stringEncodedJSON: String {
        var copy = self
        let encodingDict: [String: String] = ["\"": "\\\"", "/": "\\/", "\n": "\\n", "\u{8}": "\\b","\u{12}": "\\f", "\r": "\\r", "\t": "\\t"]
        encodingDict.forEach({ copy = copy.replacingOccurrences(of: $0, with: $1) })
        return copy
    }
}


文章来源: Objective-C - How to convert NSString to escaped JSON string?