【问题标题】:AFNetworking: Using AFJSONRequestOperation with UTF8 fileAFNetworking:将 AFJSONRequestOperation 与 UTF8 文件一起使用
【发布时间】:2012-12-24 17:54:30
【问题描述】:

我正在尝试使用 AFNetworking 异步获取 JSON。

我有一个 UTF8 编码的 json 文件,AFJSONRequestOperation 用 UTF8 代码返回我的字典:

éphémère   -->   \U00c3\U00a9ph\U00c3\U00a9m\U00c3\U00a8re

有没有办法让 UTF8 与 AFJSONRequestOperation 一起工作?

使用 AFJSONRequestOperation 存在第二个问题:他无法使用 BOM 读取 UTF8 文件。

这是我的代码:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                         JSONRequestOperationWithRequest:request
                                         success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
                                         {

                                             NSLog(@"JSON: %@", JSON);
                                         } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
                                         {
                                             NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);

                                         }];
    [operation start];

在此之前,我使用的是 JSONKit,而且效果很好(字符集 + BOM)!但我需要进行异步调用。

感谢您的帮助!

【问题讨论】:

  • \U 是无效的 JSON。请参阅json.org 的语法
  • 我的 JSON 是 {"test" : "éphémère"}。 NSLog 显示如下: JSON: { test = "\U00c3\U00a9ph\U00c3\U00a9m\U00c3\U00a8re"; }

标签: json utf-8 character-encoding afnetworking


【解决方案1】:

这是 NSLog 的问题,你的 JSON 是有效的,你可以在其中检索一个键的值并查看它的有效字符。

我使用此代码使我的响应 JSON 更具可读性:

-(NSString*)stringByReplacingUnicodePoint:(id)jsonObj
{
    NSData *data = [NSJSONSerialization dataWithJSONObject:jsonObj options:0 error:nil];
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return result;
}

-(void)networkResponse:(id)JSON
{
    NSLog(@"JSON: %@", [self stringByReplacingUnicodePoint: JSON]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-30
    • 2018-08-08
    • 2014-02-13
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    相关资源
    最近更新 更多