Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON to NSArray

I have a JSON array being output on a page. I would like to convert this JSON array into an NSArray.

This is the JSON output on the web page:

[{"city":"Current Location"},{"city":"Anaheim, CA"},{"city":"Los Angeles, CA"},{"city":"San 
Diego, CA"},{"city":"San Francisco, CA"},{"city":"Indianapolis, IN"}]

This is my NSURL call and NSJSONSerialization:

NSString *cityArrayURL = [NSString stringWithFormat:@"http://site/page.php";
NSData *cityData = [NSData dataWithContentsOfURL:[NSURL URLWithString:cityArrayURL]];

NSError *error;
NSDictionary *cityJSON = [NSJSONSerialization JSONObjectWithData:cityData 
options:kNilOptions error:&error];

I would like to turn the NSDictionary called cityJSON into an NSArray. Can someone let me know what the next step might be? Thank you!

like image 839
Brandon Avatar asked Oct 11 '14 05:10

Brandon


2 Answers

How about this?

cityArray = [[NSMutableArray alloc] init];
cityArray = [NSJSONSerialization JSONObjectWithData: cityData options:NSJSONReadingMutableContainers error:nil];
like image 51
Fahim Parkar Avatar answered Oct 03 '22 01:10

Fahim Parkar


NSString *requestString = @"http://pastebin.com/raw.php?i=iX5dZZt3";

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:requestString]];

NSError *error;
NSDictionary *cityJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSArray *cityArray = [cityJSON valueForKey:@"city"];
NSLog(@"%@",cityArray);

NSLog(@"Response is of type: %@", [cityArray class]);
like image 44
raurora Avatar answered Oct 03 '22 02:10

raurora