将JSON转换为NSArray
我有一个JSON数组在页面上输出。 我想将这个JSON数组转换成NSArray。
这是网页上的JSON输出:
[{"city":"Current Location"},{"city":"Anaheim, CA"},{"city":"Los Angeles, CA"},{"city":"San Diego, CA"},{"city":"San Francisco, CA"},{"city":"Indianapolis, IN"}]
这是我的NSURL调用和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];
我想把名为cityJSON的NSDictionary变成一个NSArray。 有人能让我知道下一步可能是什么吗? 谢谢!
这个怎么样?
cityArray = [[NSMutableArray alloc] init]; cityArray = [NSJSONSerialization JSONObjectWithData: cityData options:NSJSONReadingMutableContainers error:nil];
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]);
如果根对象是数组types, JSONObjectWithData
将返回NSArray。
尝试打印
NSLog(@"%@", [cityJSON class]);
我的Json看起来像
{"results":[{"state_name":"Ariyalur"},{"state_name":"Chennai"},{"state_name":"Coimbatore"},{"state_name":"Cuddalore"},{"state_name":"Dharmapuri"}}}]}
和我的代码是
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); } }];