UTF-8转换

3
我正在获取一个JSON数组并将其存储在NSArray中。但是,它包括JSON编码的UTF-8字符串,例如pass\u00e9代表passé。 我需要一种将所有这些不同类型的字符串转换为实际字符的方法。 我有一个整个NSArray要转换。 或者当它被显示时,我可以转换它,这取决于哪个更容易。
我找到了这张图 http://tntluoma.com/sidebars/codes/ 是否有方便的方法或我可以下载的库?
谢谢,
顺便说一下,我找不到更改服务器的方法,所以我只能在我的端上修复它...

如果使用类方法+ (id)stringWithUTF8String:(const char *)bytes创建 NSString 对象,它会正确显示吗? - catsby
您能否提供一个示例?我不熟悉使用const char。谢谢。 - leachianus
2个回答

1

您可以使用基于NSScanner的方法。以下代码(不是防错的)可以为您提供它如何工作的方式:

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);

看起来很有前途,但我不知道它如何转换每个类型的字符,例如“在细胞核中”。 - leachianus

1
如果您使用JSON Framework,那么您所要做的就是获取您的JSON字符串并将其转换为NSArray,如下所示:
NSString * aJSONString = ...;
NSArray * array = [aJSONString JSONValue];

这个库写得很好,会自动处理UTF8编码,所以你不需要做任何额外的工作。我在几个已经上架的应用中多次使用了这个库。我强烈建议采用这种方法。


我已经在做这个:NSURL *url = [NSURL URLWithString:string];NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url]; NSDictionary *dict = [jsonreturn JSONValue]; - leachianus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接