(Obj-C)使用NSHTTPURLResponse(allHeaderFields)中的词典中的重音来解码JSON

时间:2015-12-10 15:40:33

标签: ios objective-c json dictionary

我以这种方式接收来自NSHTTPURLResponse的头字段作为NSDictionary:

NSHTTPURLResponse *response = ((NSHTTPURLResponse *)[task response]);
NSDictionary *rootDictionary = [response allHeaderFields];

但是这个词典的值有重音,当我尝试显示为Alert时,会出现符号而不是带重音的字母。我用这种方式:

NSError * err;
NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:[response allHeaderFields] options:0 error:&err];

id rootObject = [NSJSONSerialization
                   JSONObjectWithData:jsonData
                              options:0
                                error:&error];

NSDictionary *rootDictionary = rootObject;

在我的标题中,我收到了这个:

headers {
    "Cache-Control" = "no-cache";
    Connection = "Keep-Alive";
    "Content-Language" = en;
    "Content-Length" = 30;
    "Content-Type" = "text/plain; charset=utf-8";
    Date = "Thu, 10 Dec 2015 15:47:07 GMT";
    Expires = "-1";
    "Keep-Alive" = "timeout=5, max=100";
    Pragma = "no-cache";
    Server = "xxxxxxxxxx";
    "X-AspNet-Version" = "xxxxx";
    "X-Error" = "Par\U00c3\U00a1metros faltantes";
    "X-Powered-By" = "xxxxxx";
}

我在警告中显示了X-Error值:

NSString *description = [rootDictionary objectForKey:@"X-Error"];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Title of my alert" message:description delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok", nil) otherButtonTitles:nil];
          [alert show];

这是我的结果:

  

Parámetrosfaltantes

这是我在Xcode(NSLog)中的字典日志:

{
    "Cache-Control" = "no-cache";
    Connection = "Keep-Alive";
    "Content-Language" = en;
    "Content-Length" = 30;
    "Content-Type" = "text/plain; charset=utf-8";
    Date = "Thu, 10 Dec 2015 16:13:00 GMT";
    Expires = "-1";
    "Keep-Alive" = "timeout=5, max=100";
    Pragma = "no-cache";
    Server = "xxxxxx";
    "X-AspNet-Version" = "xxxxxx";
    "X-Error" = "Par\U00c3\U00a1metros faltantes";
    "X-Powered-By" = "xxxxx";
}

任何人都有其他解决方案吗?

1 个答案:

答案 0 :(得分:0)

答案:

我可以这样做:

NSDictionary *headerField = [response allHeaderFields];
NSString *description = [headerField valueForKey:@"X-Error"];
NSString *correctString = [NSString stringWithCString:[description cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];

重要元素是 cStringUsingEncoding:NSISOLatin1StringEncoding 。而correctString正确地给了我口音!