gpt4 book ai didi

ios - 将 NSData 转换为 NSDictionary

转载 作者:可可西里 更新时间:2023-11-01 05:39:51 24 4
gpt4 key购买 nike

我正在尝试从 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);

最佳答案

在使用 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);
}

关于ios - 将 NSData 转换为 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48661465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com