2010-04-26 36 views
4

嘿,我抓住一个JSON数组并将其存储在NSArray中,但它包含JSON编码的UTF-8字符串,例如pass \ u00e9表示passé。我需要一种将所有这些不同类型的字符串转换为实际字符的方法。我有一整个NSArray转换。或者我可以在显示时转换它,这是最简单的。UTF-8转换

我发现这个图表http://tntluoma.com/sidebars/codes/

是有这个方便的方法还是可以下载一个图书馆吗?

感谢,

顺便说一句,有没有办法,我可以找到改变服务器,所以我只能修复它在我结束...

+0

如果使用类方法'+(id)stringWithUTF8String:(const char *)bytes'创建'NSString'对象,它会正确显示吗? – catsby 2010-04-26 13:16:01

+0

你能提供一个例子吗?我不熟悉使用const char。 感谢 – leachianus 2010-04-26 15:47:55

回答

1

您可以使用基于NSScanner的方法。下面的代码(不是bug的证明)可以为您提供有关它如何工作的方式:如果您使用JSON Framework

NSString *source = [NSString stringWithString:@"Le pass\\u00e9 compos\\u00e9 a \\u00e9t\\u00e9 d\\u00e9compos\\u00e9."]; 
NSLog(@"source=%@", source); 

NSMutableString *result = [[NSMutableString alloc] init]; 
NSScanner *scanner = [NSScanner scannerWithString:source]; 
[scanner setCharactersToBeSkipped:nil]; 
while (![scanner isAtEnd]) { 
    NSString *chunk; 

    // Scan up to the Unicode marker 
    [scanner scanUpToString:@"\\u" intoString:&chunk]; 
    // Append the chunk read 
    [result appendString:chunk]; 

    // Skip the Unicode marker 
    if ([scanner scanString:@"\\u" intoString:nil]) { 

     // Read the Unicode value (assume they are hexa and four) 
     unsigned int value; 
     NSRange range = NSMakeRange([scanner scanLocation], 4); 
     NSString *code = [source substringWithRange:range]; 
     [[NSScanner scannerWithString:code] scanHexInt:&value]; 
     unichar c = (unichar) value; 

     // Append the character 
     [result appendFormat:@"%C", c]; 

     // Move the scanner past the Unicode value 
     [scanner scanString:code intoString:nil]; 
    } 
} 

NSLog(@"result=%@", result); 
+0

看起来很有希望,但我看不出它如何将每一种类型的字符转换,例如“位于小区'彗核” – leachianus 2010-04-26 15:52:46

1

,然后你要做的就是让你的JSON字符串,并将其转换为NSArray像这样:

NSString * aJSONString = ...; 
NSArray * array = [aJSONString JSONValue]; 

这个库编写得很好,并且会自动处理UTF8编码,所以除了这个之外你不需要做任何事情。我在商店的应用中多次使用过这个库。我高度推荐使用这种方法。

+0

我已经这样做了: \t NSURL * URL = [NSURL URLWithString:字符串] ; \t NSString * jsonreturn = [[NSString alloc] initWithContentsOfURL:url]; \t \t NSDictionary * dict = [jsonreturn JSONValue]; – leachianus 2010-04-26 15:54:21