从JSON结果格式化欧洲字符

时间:2009-09-06 13:28:48

标签: objective-c iphone

我正在构建一个导入JSON结果并将对象解析为表格单元格的应用程序。没有什么花哨的,但在我的结果中,许多术语/名称都是欧洲语,其中包括è或ú等字符,它们的格式为\ u00E9或\ u00FA。我认为这些是ASCII?还是unicode? (我永远不能保持直率)。无论如何,像所有好的NSSTring一样,我认为必须有一种方法来解决这个问题,但我找不到它......任何想法?我试图避免做这样的事情:this posting。谢谢大家。

2 个答案:

答案 0 :(得分:1)

正如kaizer.se所指出的,这些是unicode字符。您可以使用的NSString方法是+ stringWithContentsOfURL。或+ s​​tringWithContentsOfFile。例如:

NSError *error;
NSString *incoming = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://sender.org"] encoding:NSUnicodeStringEncoding error:&error];

答案 1 :(得分:0)

所以你在谈论unicode转义序列。它们只是字符代码,可以使用printf样式的'%C'进行转换。

NSScanner可能是一个很好的方法来做到这一点......这是一个裂缝(ew):

NSString* my_json = @"{\"key\": \"value with \\u03b2\"}";
NSMutableString* clean_json = [NSMutableString string];
NSScanner* scanner = [NSScanner scannerWithString: my_json];
NSString* buf = nil;
while ( ! [scanner isAtEnd] ) {
    if ( ! [scanner scanUpToString: @"\\u" intoString: &buf] )
        break;//no more characters to scan
    [clean_json appendString: buf];
    if ( [scanner isAtEnd] )
        break;//reached end with this scan
    [scanner setScanLocation: [scanner scanLocation] + 2];//skip the '\\u'
    unsigned c;
    if ( [scanner scanHexInt: c] )
        [clean_json appendFormat: @"%C", c];
    else
        [clean_json appendString: @"\\u"];//nm
}
// 'clean_json' is now a string with unicode escape sequences 'fixed'