将JSON转换为NSArray

时间:2014-10-11 05:55:34

标签: ios objective-c nsarray nsjsonserialization

我在页面上输出了一个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。有人能告诉我下一步可能是什么吗?谢谢!

4 个答案:

答案 0 :(得分:10)

这个怎么样?

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

答案 1 :(得分: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]);

答案 2 :(得分:1)

如果根对象是数组类型,

JSONObjectWithData将返回NSArray。

尝试打印

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

答案 3 :(得分:0)

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