iosjsonobjective-cparsing

Parse JSON data in iOS


I know it's a common question, but I am stuck with is API.

How to Parse data from this API: http://dl.bahramradan.com/api/1/get/ig

It contains 20 Object and in every object there are 3 other Objects called "image", date" and "caption".

How can I store all "date" values in an NSMUtableArray in iOS?

I did this:

NSString *urlStr = [NSString stringWithFormat:@"http://dl.bahramradan.com/api/1/get/ig"];
NSURL *url = [NSURL URLWithString:urlStr];
NSData *json = [NSData dataWithContentsOfURL:url];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:json options:0 error:NULL];

NSArray *dateArray = [dict objectForKey:@"date"];

But when I run my app, it crashes on the last line, what is wrong?


Solution

  • I did not check, if your JSON is valid. But there is one obvious mistake in your code: If the JSON consists of 20 objects, I assume those being contained in an array, rather than in a dict!

    So first thing to change is

    NSArray *array = [NSJSONSerialization JSONObjectWithData:json options:0 error:NULL];
    

    Then, you want to extract the 'date' values for all items and combine these in another array. Easiest way to achieve that, is by using a KVC Collection Operator

    NSArray *dateArray = [array valueForKeyPath:@"@unionOfObjects.date"];
    

    So, what '@unionOfObjects.date' does, is: going through all the objects in the array, look for each of their 'date' value and combine them in the returned array. Check out this excellent post about KVC Collection Operators!