简体   繁体   English

将 NSData 转换为 NSDictionary

[英]Converting NSData to NSDictionary

I am trying to fetch data from an url https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json我正在尝试从 url https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json获取数据

I am getting nil while converting nsdata to nsdictionary.我在将 nsdata 转换为 nsdictionary 时得到了 nil。

I used the following code.我使用了以下代码。 and I am able to log the data as well.我也可以记录数据。 but as soon as I convert it into dictionary it is showing nil.What am I missing here?但是一旦我将其转换为字典,它就会显示为零。我在这里错过了什么?

I tried nsurlsession and afnetworking as well.我也试过 nsurlsession 和 afnetworking。 getting the same error.得到同样的错误。

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);

You have to convert NSData into UTF8 before parsing it using NSJSONSerialization .在使用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);
}

If you are looking for the Swift equivalent of Jayesh Thanki's Objective-C code, here it is,如果您正在寻找与 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM