如何为UIWebView转义字符串?

neo*_*eye 2 json escaping uiwebview nsstring ios

我从服务器中提取json数据.它包含一个带有文本的字典,我将其插入到html模板中.

如何正确地逃避这个字符串?

NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json someEscapeMethod]; ///////  HOW TO ESCAPE THIS ?
NSString* script = [NSString stringWithFormat:@"process('%@')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];
Run Code Online (Sandbox Code Playgroud)

我目前这样做,但我不确定逃跑是否充分

NSString* json_escaped = [json stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
Run Code Online (Sandbox Code Playgroud)

neo*_*eye 6

我现在用这种方式编码,但开销很大.

NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* script = [NSString stringWithFormat:@"process('%@')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];
Run Code Online (Sandbox Code Playgroud)

并在这样的JavaScript中解码它

function process(json_escaped) {
  var json = decodeURIComponent(json_escaped);
  alert('json: ' + json.toString());
}
Run Code Online (Sandbox Code Playgroud)

我仍在寻找更好的解决方案,减少开销.

更新

我最近了解到,存在几个用javascript来桥接objective-c的框架.