将NSData转换为NSDictionary

8

我正试图从以下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]是否为nil?你有检查过error吗?既然有关于AFNetworking/NSURLSession 的问题,为什么还要使用 dataWithContentsOfURL:呢? - Larme
我只想知道问题出在哪里。因为代码很简单,我已经在问题中提供了它。 - Sekhar
1
我尝试了你的代码,错误信息显示: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。该字符似乎无效。 - Larme
你是怎么得到那个错误的?我用 JSON Lint 进行了验证,结果是正常的。即使在浏览器中也显示为正确的 JSON。 - Sekhar
@Sekhar,我也查看了该URL并得到了相同的结果,然后我检查了JSON结构,它是有效的,但是很可能您的字符无效 -> 请查看https://dev59.com/Y2gu5IYBdhLWcg3wpYnJ - dahiya_boy
显示剩余2条评论
2个回答

12

在使用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
如果你正在寻找Jayesh Thanki的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接