代码:
NSURL * url=[NSURL URLWithString:@"alamghareeb.com/mobileData.ashx?catid=0&No=10"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSMutableArray * referanceArray=[[NSMutableArray alloc]init];
NSMutableArray * periodArray=[[NSMutableArray alloc]init];
NSArray * responseArr = [NSArray arrayWithArray:json[@"item"]];
for (NSDictionary * dict in responseArr) {
[referanceArray addObject:[dict objectForKey:@"created"]];
}
JSON看起来像:
{
"item" = [
{
"id" : "2292",
"created" : "10/01/2015 10:21:18 ص",
"title" : "الإمارات: ملابس رياضية فاخرة لتحسين أداء الإبل في السباقات ",
"image_url" : "http://alamghareeb.com/Photos/L63556482078696289044.jpg",
"image_caption" : ""
},
{
"id" : "2291",
"created" : "10/01/2015 09:28:11 ص",
"title" : "طبيبة تجميل 'مزورة' تحقن مرضاها بالغراء والاسمنت",
"image_url" : "http://alamghareeb.com/Photos/L63556478891290039015.jpg",
"image_caption" : ""
}
]
}
答案 0 :(得分:3)
此JSON无效。你手动构建它了吗? "item" = ...
应为"item" : ...
。
将来,您可以通过http://jsonlint.com运行JSON来验证任何问题。同样,您应该在Objective-C代码中添加错误检查,例如
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
if (!json) {
NSLog(@"JSON parsing error: %@", error);
}
我还建议将服务器代码更改为不手动构建JSON,但要利用JSON函数(例如,如果使用PHP,构建关联数组,然后使用json_encode
函数生成JSON输出)。
因此,一旦修复了JSON错误,解析结果可能如下所示:
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!dictionary) {
NSLog(@"NSJSONSerialization error: %@", error);
return;
}
NSArray *items = dictionary[@"item"];
for (NSDictionary *item in items) {
NSString *identifier = item[@"id"];
NSString *created = item[@"created"];
NSString *title = item[@"title"];
NSString *urlString = item[@"image_url"];
NSString *caption = item[@"image_caption"];
NSLog(@"identifier = %@", identifier);
NSLog(@"created = %@", created);
NSLog(@"title = %@", title);
NSLog(@"urlString = %@", urlString);
NSLog(@"caption = %@", caption);
}
答案 1 :(得分:0)
您可以使用NSJSONSerialization
。无需导入任何类。
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[strResult dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
或直接使用NSData
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:theJSONDataFromTheRequest options:0 error:nil];