【问题标题】:Converting NSData to NSDictionary将 NSData 转换为 NSDictionary
【发布时间】:2018-07-17 14:31:19
【问题描述】:

我正在尝试从 URL https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json 获取数据

在将 nsdata 转换为 nsdictionary 时,我得到了 nil。

我使用了以下代码。我也可以记录数据。但是一旦我将它转换成字典,它就会显示 nil。我在这里错过了什么?

我也尝试过 nsurlsession 和 afnetworking。得到同样的错误。

NSError *error;
NSString *url_string = [NSString stringWithFormat: DATA_URL];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"json: %@", json);

【问题讨论】:

  • dataWithContentsOfURL::不推荐,这会阻塞当前的 UI。另外,[NSURL URLWithString:url_string] 是零吗?你检查error了吗?有关于 AFNetworking/NSURLSession 的问题,但您使用 dataWithContentsOfURL:
  • 我只是想知道问题出在哪里。因为代码很简单,所以我在问题中给出了。
  • 我试过你的代码,错误提示:Error Domain=NSCocoaErrorDomain Code=3840 "Unable to convert data to string around character 2643." UserInfo={NSDebugDescription=Unable to convert data to string around character 2643.}。然后执行[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] substringWithRange:NSMakeRange(2643-5, 10)] 给出:ion":"ノare。该字符似乎无效。
  • 你是怎么得到这个错误的。我用 json lint 验证了它,结果是肯定的。即使在浏览器中,它也显示了正确的 json。
  • @Sekhar 我还检查了这个 url 并得到了相同的结果,然后我检查了 json 结构,它是有效的,但可能你的字符无效 -> 检查stackoverflow.com/questions/11174130/…

标签: ios objective-c json afnetworking nsurlsession


【解决方案1】:

在使用 NSJSONSerialization 解析之前,您必须将 NSData 转换为 UTF8。

NSError* error = nil;

NSString *strISOLatin = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSData *dataUTF8 = [strISOLatin dataUsingEncoding:NSUTF8StringEncoding];

id dict = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:0 error:&error];
if (dict != nil) {
    NSLog(@"Dict: %@", dict);
} else {
    NSLog(@"Error: %@", error);
}

【讨论】:

  • 拯救了我的一天。谢谢。
【解决方案2】:

如果您正在寻找 JayeshThanki 的 Objective-C 代码的 Swift 等价物,这里就是,

let str = String(data: d, encoding: .isoLatin1)
let data8 = str?.data(using: .utf8)
let result = try JSONSerialization.jsonObject(with: data8!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多