2013-04-05 2 views
4

내가 \ n, 따옴표를 포함 \, /, \ R 수있는 NSString가 있고, 나는이Objective-C - NSString을 이스케이프 처리 된 JSON 문자열로 변환하는 방법은 무엇입니까?

"text1\text2"

같은 문자열 있도록 JSON 인코딩 된 문자열로 변환 할은

\"text1\\text2\"

된다

내가 할 수있게 해주는 기존 기능이 있습니까?

또한 SBJson을 프로젝트에 사용하고 있지만 SBJson이이 작업을 수행 할 수 있는지 여부를 확인할 수 없습니다. 내 응용 프로그램이 여전히 OSX 10.6

답변

11

이 귀하의 질문에 대답합니까 지원해야하기 때문에

NSJSONSerialization 테이블에 있지?

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

자료 : converting NSString to JSON string

+0

방법에 대한 인쇄 할 수없는 문자를 이스케이프 처리하기위한 몇 줄의 코드? '\ U1234' 등 –

+0

유니 코드 문자가 올바르게 처리되지 않았습니까? (http://json.org) – Jean

+0

예. 고맙습니다! – lakeskysea

0

스위프트 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."

+0

'\ n '을'\\ n '으로 바꾸면 안됩니까? – Crashalot

1

의 더 - 네이티브 JSON-방법으로 그것을 할 수 있도록, u는 내 대답을 좋아하는 경우에, 솔루션 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]; 
0

에서 스위프트 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 
    } 
}