(Obj-C) 从 NSHTTPURLResponse (allHeaderFields) 解码带有重音符号的 JSON

Posted

技术标签:

【中文标题】(Obj-C) 从 NSHTTPURLResponse (allHeaderFields) 解码带有重音符号的 JSON【英文标题】:(Obj-C) Decode JSON with accents in Dictionary from NSHTTPURLResponse (allHeaderFields) 【发布时间】:2015-12-10 15:40:33 【问题描述】:

我以这种方式从 NSHTTPURLResponse 作为 NSDictionary 接收标头字段:

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

但是在这本字典的值中有重音符号,当我尝试显示为警报时,会出现符号而不是带有重音符号的字母。我是这样用的:

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ámetros falantes

这是我在 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";

有人有其他解决方案吗?

【问题讨论】:

您需要使用有关您拥有的数据和所看到的结果的更多详细信息来更新您的问题。 准备好了@rmaddy,我更新了 使用rootDictionaryNSLog 输出更新您的问题,并显示用于从rootDictionary 获取警报的代码。 【参考方案1】:

答案:

我可以这样做:

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

重要的元素是cStringUsingEncoding:NSISOLatin1StringEncoding。并且正确的字符串正确地给我重音!

【讨论】:

以上是关于(Obj-C) 从 NSHTTPURLResponse (allHeaderFields) 解码带有重音符号的 JSON的主要内容,如果未能解决你的问题,请参考以下文章

从 C++ 函数访问 Obj-C 属性 (iOS)

从具有属性的 NSObject 转换为 NSDictionary 的 Obj-C 简单方法?

将字符串从 Obj-C 传递到 React Native

Obj-C 应用程序不会从一开始就加载

如何从 obj-c / ios 中的堆栈跟踪中获取源代码行

在类 Obj-C 之间发送消息?