2014-10-11 3 views
5

페이지에 JSON 배열이 출력됩니다. 이 JSON 배열을 NSArray로 변환하고 싶습니다. 이건 내 NSURL 호출하고 NSJSONSerializationJSON을 NSArray로 변환

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

입니다 :

는 웹 페이지에서 JSON의 출력 내가 NSDictionary에가로 cityJSON라고 설정하고 싶은

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

NSArray. 누군가가 다음 단계가 무엇인지 알 수 있습니까? 고맙습니다!

답변

10

어때요? 루트 객체가 배열 유형 인 경우

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

JSONObjectWithData이있는 NSArray를 반환합니다.

한번에 인쇄

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

{"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); 
      } 
     }]; 
처럼 내 JSON은 같은데