Ios 使用NSURLSession中断结果读取JSON
如前所述,我正在从URL读取JSON文件。若我访问这个页面,JSON格式是有效的并且很好。在应用程序中,我通过以下方式获得:Ios 使用NSURLSession中断结果读取JSON,ios,objective-c,json,nsurlsession,nsjsonserialization,Ios,Objective C,Json,Nsurlsession,Nsjsonserialization,如前所述,我正在从URL读取JSON文件。若我访问这个页面,JSON格式是有效的并且很好。在应用程序中,我通过以下方式获得: NSURLSession *session = [NSURLSession sharedSession]; [[session dataTaskWithURL:[NSURL URLWithString:urlAsString] completionHandler:^(NSData *data, NSU
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:urlAsString]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (error) {
NSLog(@"Error");
} else {
alreadyParsed = true;
NSMutableDictionary* object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSMutableDictionary *posts = [object valueForKey:@"posts"];
if (!object) {
NSLog(@"Error parsing JSON: %@", error);
} else {
for (NSMutableDictionary *item in posts) {
NSLog(@"Item: %@", item);
}
}
NSLog(@"Data: %@", [object description]);
}
}] resume];
在第页上,JSON看起来像:
{
"status": "ok",
"count": 1,
"count_total": 39,
"pages": 39,
"posts": [
{
"id": 948564,
"title": "",
"modified": "2016-02-17 21:32:26",
"attachments": [],
"attachments_featured": [
{}]
},
{
"id": 948565,
"title": "",
"modified": "2016-02-17 21:32:26",
"attachments": []
}]
}
但在应用程序中,我得到:
2016-02-29 17:04:34.819 test[22835:1929421] Data: {
count = 1;
"count_total" = 39;
pages = 39;
posts = (
{
attachments = (
);
.
.
.
在posts数组和附件之间应该有更多的数据,但我不知道发生了什么以及为什么不显示
我试着把页面数据转换成字符串并打印出来,结果显示很好。还尝试将该字符串转换为NSData并创建JSON,但结果是一样的。有人知道发生了什么吗?对象没有排序,因此在运行代码时,数据也可能位于“附件”之后。您刚才键入“…”得到了什么?Stefan您是对的,数据未排序,位于附件下方。我将在稍后的代码中解析这些数据,它以前是有效的。代码和服务器端都没有任何变化,它突然停止了工作。困扰我的是,在应用程序的输出中没有[括号,有;字符,这是JSON没有的。这是某种调试器输出吗?
NSLog()
使用description
方法,输出的格式正是编写description
的苹果开发人员喜欢的格式。有些字符串没有引用,有些是,这在Swift中得到了解决。description
甚至没有尝试生成JSON,NSData
早于JSON。我注意到有一些数据丢失,例如我的应用程序中的“附件”是空的。这是我数据的主要部分。这很奇怪,因为我没有对结果做任何事情。