2014-10-11 14 views
5

Ho un array JSON in uscita su una pagina. Vorrei convertire questo array JSON in un NSArray.Converti JSON in NSArray

Questa è l'uscita JSON sulla pagina web:

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

Questo è il mio invito NSURL e 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]; 

Vorrei girare il NSDictionary chiamato cityJSON in un NSArray. Qualcuno può farmi sapere quale potrebbe essere il prossimo passo? Grazie!

risposta

10

Che ne dici di questo?

cityArray = [[NSMutableArray alloc] init]; 
cityArray = [NSJSONSerialization JSONObjectWithData: cityData options:NSJSONReadingMutableContainers error:nil]; 
1

JSONObjectWithData restituirà il NSArray se oggetto principale è di tipo matrice.

provare a stampare

NSLog(@"%@", [cityJSON class]); 
3
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]); 
0

mio JSON Sembra

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

e il mio codice è

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); 
      } 
     }];