将某些字符转换为转义的unicode版本

时间:2012-09-09 18:56:46

标签: objective-c ios cocoa-touch

我有一个NSString包含可能不需要的字符,我必须转换为转义的unicode版本。更具体地说,我需要通过它的脚本评估方法将JSON对象(序列化为字符串)传递给UIWebView,并且某些字符往往会引发JS异常。

所以我想对JSLint提到的所有字符进行编码是不安全的:

\u0000-\u001f
\u007f-\u009f
\u00ad
\u0600-\u0604
\u070f
\u17b4
\u17b5
\u200c-\u200f
\u2028-\u202f
\u2060-\u206f
\ufeff
\ufff0-\uffff

并用他们的转义等价物替换它们。

最好的方法是什么?

UPDATE :不知何故{J}

<{1}}(行分隔符char)

1 个答案:

答案 0 :(得分:0)

嗯,这不是我想到的解决方案,但修剪也是一个合适的选择

  // Remove unsafe JSON characters
  //
  // http://www.jslint.com/lint.html#unsafe
  //
  if (jsonStr.length > 0) {
    NSMutableCharacterSet *unsafeSet = [NSMutableCharacterSet new];
    void (^addUnsafe)(NSInteger, NSInteger) = ^(NSInteger from, NSInteger to) {
      if (to > from) {
        [unsafeSet addCharactersInRange:NSMakeRange(from, (to - from) + 1)];
      } else {
        [unsafeSet addCharactersInRange:NSMakeRange(from, 1)];
      }          
    };

    addUnsafe(0x0000, 0x001f);
    addUnsafe(0x007f, 0x009f);
    addUnsafe(0x00ad, 0);
    addUnsafe(0x0600, 0x0604);
    addUnsafe(0x070f, 0);
    addUnsafe(0x17b4, 0);
    addUnsafe(0x17b5, 0);
    addUnsafe(0x200c, 0x200f);
    addUnsafe(0x2028, 0x202f);
    addUnsafe(0x2060, 0x206f);
    addUnsafe(0xfeff, 0);
    addUnsafe(0xfff0, 0xffff);

    jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:unsafeSet] componentsJoinedByString:@""];
  }