Reputation: 27
The code:
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"]];
}
The JSON looks like:
{
"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" : ""
}
]
}
Upvotes: 1
Views: 127
Reputation: 2698
You can use NSJSONSerialization
. No need to import any class.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[strResult dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
or use NSData
directly as
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:theJSONDataFromTheRequest options:0 error:nil];
Source : Stackoveflow question
Upvotes: 0
Reputation: 437452
This JSON is not valid. Did you build it manually? The "item" = ...
should be "item" : ...
.
In the future, you can run your JSON through http://jsonlint.com to verify any issues. Likewise, you should add error checking in your Objective-C code, e.g.
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
if (!json) {
NSLog(@"JSON parsing error: %@", error);
}
I'd also suggest changing your server code to not build JSON manually, but take advantage of JSON functions (e.g. if PHP, build associative arrays and then generate JSON output using the json_encode
function).
So, once you fix the JSON error, to parse the results might look like:
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);
}
Upvotes: 3