我正在尝试从 url https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json 获取数据
我在将 nsdata 转换为 nsdictionary 时得到了 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);
最佳答案
在使用 NSData
解析它之前,您必须将 NSJSONSerialization
转换为 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);
}
关于ios - 将 NSData 转换为 NSDictionary,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48661465/