NSJSONSerializzation没有正确读取UTF8

时间:2015-05-17 16:31:23

标签: ios objective-c uitableview utf-8

我正在从网址上读取JSON。它是UTF8格式。当我加载UITableView它显示不正确的字符。 请在第2行enter image description here

找到附带的屏幕截图

读取数据的代码如下:

NSURL *myURL=[NSURL     URLWithString:@"http://www.bancariromani.it/cecadm/newClass/modules/rh/index.php?id_cup=15&json=1"];

NSError *error;
NSData *myData=[[NSData alloc]initWithContentsOfURL:myURL];
if(!myData){

    return;

}

NSArray *jasonArray=[NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];

我还没试过就试过这个:

NSURL *myURL=[NSURL URLWithString:@"http://www.bancariromani.it/cecadm/newClass/modules/rh/index.php?id_cup=15&json=1"];

 NSError *error;
NSString *string = [NSString stringWithContentsOfURL:myURL encoding:NSISOLatin1StringEncoding error:nil];

 NSData *myData = [string dataUsingEncoding:NSUTF8StringEncoding];

if(!myData){

    return;

}
NSArray *jasonArray=[NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];

我在哪里丢失UTF8格式?

感谢您的帮助

的Dario

3 个答案:

答案 0 :(得分:2)

您的数据使用HTML方式存储特殊字符。它与UTF-8不同,是一种使用ASCII码点添加特殊字符的方法。

请参阅http://www.w3.org/TR/html4/charset.html#h-5.3了解其工作原理。在HTML character decoding in Objective-C / Cocoa Touch中回答了解码它们的方法。

答案 1 :(得分:0)

你的意思是" ' "第二排?那个HTML,你可以通过做url编码来转换它。你可以试试这个方法:

- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

答案 2 :(得分:0)

'是角色的HTML转义;这完全与UTF-8无关。

要么让你的WebService停止使用百分比转义来编码HTML实体,因为通常不需要他们这样做......或者你可以使用一种方法来删除它们,就像这段代码一样:

NSMutableString* yourString = [… mutableCopy];
CFStringTransform((CFMutableStringRef)yourString, NULL, kCFStringTransformToXMLHex, true);
NSLog(@"transformed string: %@", yourString);

不幸的是,这似乎仅适用于表示为十六进制代码点的HTML实体,如',而不是表示为十进制代码点的实体,如&#039

所以这是一个自定义方法(解码十进制HTML实体):

NSString* decodeHTMLEntities(NSString* string)
{
    NSRegularExpression* decimalEntity = [NSRegularExpression regularExpressionWithPattern:@"&#(\\d+);" options:0 error:nil];
    NSMutableString* resultString = [string mutableCopy];
    NSInteger __block offset = 0;
    [decimalEntity enumerateMatchesInString:string options:0 range:NSMakeRange(0,string.length)
                                 usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
     {
         unsigned decimalCode = [string substringWithRange:[result rangeAtIndex:1]].intValue;
         NSString* decodedChar = [NSString stringWithFormat:@"%C", (unichar)decimalCode];
         result = [result resultByAdjustingRangesWithOffset:offset];
         [resultString replaceCharactersInRange:result.range withString:decodedChar];
         offset += (NSInteger)decodedChar.length - (NSInteger)result.range.length;
     }];
    return [resultString copy];
}

(当然,要求您的WebService提供商在源头修复它会更好,因为他们没有正当理由这样做)

相关问题