Convert JSON to NSArray

I have a JSON array that is being output to a page. I would like to convert this JSON array to 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 call to NSURL 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 an NSDictionary named cityJSON into an NSArray. Can someone tell me what the next step can take? Thanks!

+5
source share
4 answers

How about this?

 cityArray = [[NSMutableArray alloc] init]; cityArray = [NSJSONSerialization JSONObjectWithData: cityData options:NSJSONReadingMutableContainers error:nil]; 
+10
source
 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]); 
+3
source

JSONObjectWithData will return an NSArray if the root object is an array type.

Try printing

 NSLog(@"%@", [cityJSON class]); 
+1
source

My Json Looks Like

 {"results":[{"state_name":"Ariyalur"},{"state_name":"Chennai"},{"state_name":"Coimbatore"},{"state_name":"Cuddalore"},{"state_name":"Dharmapuri"}}}]} 

and my code

  NSMutableArray pickerArray = [[NSMutableArray alloc]init]; NSString *urlAsString = @"urlLink"; NSURL *url = [[NSURL alloc] initWithString:urlAsString]; NSLog(@"%@", urlAsString); [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (error) { NSLog(@"%@",error.localizedDescription); } else { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; NSLog(@"Cites: %@", [json valueForKey:@"results"]); NSMutableArray *rArray = [json valueForKey:@"results"]; NSLog(@"%@",rArray); for(int i=0; i<rArray.count ; i++) { NSDictionary *dict = [rArray objectAtIndex:i]; [pickerArray addObject:[dict objectForKey:@"state_name"]]; } NSLog(@"The array is = %@", pickerArray); } }]; 
0
source

Source: https://habr.com/ru/post/1204464/


All Articles