NSJSONSerialization:正确处理特殊字符

时间:2013-02-22 18:03:30

标签: objective-c json cocoa

我想使用JSON文件中的在线数据。它目前正在工作,但当我使用特殊字符时,它显示“null”。这是我正在使用的代码:

NSString *urlString = [NSString stringWithFormat:@"http://belesios.com/burc/koc2.php"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"%@", json);
NSString *ciktiText = [[NSString alloc] initWithFormat:@"%@", json];
[kocLabel setText:ciktiText];

例如,如果我的文件包含ç或ü,则返回null。我需要做什么?

1 个答案:

答案 0 :(得分:4)

尝试使用此方法查找从服务器提取数据时使用的编码:

NSStringEncoding encoding;
NSString *jsonString =[NSString stringWithContentsOfURL:URL usedEncoding:&encoding error:&error];
if (error)
    NSLog(@"Error: %@", error);

您应该检查服务器返回的数据的编码。你的代码是正确的但你应该添加一些检查,如果错误!= nil然后不执行并显示或记录它。

NSString *jsonString = @"{\"abc\":\"ç or ü\"}";
NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
NSLog(@"Output: %@", jsonObj);

输出:{abc =“\ U00e7或\ U00fc”; 如果您使用Fiddler或其他软件打印原始响应,这就是使用编码字符的服务器响应的样子。

目前您的数据看起来像UTF8编码的字符应该像 \ U00e7 enter image description here

相关问题