2012-09-09 62 views
0

我有一個NSString包含可能不需要的字符,我必須將其轉換爲轉義的unicode版本。更具體地說,我需要通過腳本評估方法將JSON對象(作爲字符串序列化)傳遞給UIWebView,並且某些字符傾向於引發JS異常。將某些字符轉換爲逃逸的unicode版本

所以我想編碼它們提及的JSLint是不安全的所有字符:

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

,並與他們逃脫等同替換它們。

這樣做的最好方法是什麼?

UPDATE:不知何故\u2028(行分隔符字符)在J​​SON

回答

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:@""]; 
    }