스위프트 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."
방법에 대한 인쇄 할 수없는 문자를 이스케이프 처리하기위한 몇 줄의 코드? '\ U1234' 등 –
유니 코드 문자가 올바르게 처리되지 않았습니까? (http://json.org) – Jean
예. 고맙습니다! – lakeskysea