JSON parsing using NSJSONSerialization in iOS

后端 未结 6 1182
孤街浪徒
孤街浪徒 2020-12-05 16:36

I am parsing a JSON in my code. But I am getting some unexpected issues while retrieving data of parsed JSON. So let me explain my problem.

相关标签:
6条回答
  • 2020-12-05 17:10

    By serializing the data, u get a json object. Json object and dictionary are different a bit.

    Instead of using:

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    

    use:

    NSDictionary    *json    =   (NSDictionary*) data;
    
    0 讨论(0)
  • 2020-12-05 17:14

    When you see braces like that, it represents an array, not a dictionary. Your JSON also shows that by enclosing the data in brackets ('[' and ']'). So:

    RESPONSE =(
                    {
                email = "abc@gmail.com";
                id = 20;
                location = "31.000,71.000";
                phone = 1234567890;
                username = john;
            }
    );
    

    RESPONSE is an Array of Dictionaries. To access the data, iterate through the array:

    for (NSDictionary *responseDictionary in [JSONDictionary objectForKey:@"RESPONSE"]) {
            NSString *name = [responseDictionary objectForKey:@"username"];
            .....
    }
    

    or grab a dictionary at an index:

    NSDictionary *responseDictionary = [[JSONDictionary objectForKey:@"RESPONSE"] objectAtIndex:0];
    NSString *name = [responseDictionary objectForKey:@"username"];
    

    Whenever in doubt, log the the class:

    NSLog(@"%@", [[dictionary objectForKey:@"key"] class]);
    

    to see what is being returned from the dictionary.

    0 讨论(0)
  • 2020-12-05 17:16

    pragma mark - Checking Reachability and Parsing Datas

    NSString *urlString = [NSString stringWithFormat: @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.021459,76.916332&radius=2000&types=atm&sensor=false&key=AIzaSyD7c1IID7zDCdcfpC69fC7CUqLjz50mcls"];
    NSURL *url = [NSURL URLWithString: urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];
    array = [[NSMutableArray alloc]init];
    array = [[jsonData objectForKey:@"results"] mutableCopy];
    [jsonTableview reloadData];}
    

    pragma mark- UITableView Delegate

      - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
     }
    
     - (NSInteger)tableView:(UITableView *)tableView          
     numberOfRowsInSection:(NSInteger)section {
    
    return array.count;
      }
    
     - (UITableViewCell *)tableView:(UITableView *)tableView    
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
      static NSString *cellid = @"cell";
    UITableViewCell *cell = [tableView       
     dequeueReusableCellWithIdentifier:cellid];
    cell = [[UITableViewCell   
     alloc]initWithStyle:UITableViewCellStyleSubtitle    
      reuseIdentifier:cellid];
    
    cell.textLabel.text = [[array    
     valueForKeyPath:@"name"]objectAtIndex:indexPath.row];
    cell.detailTextLabel.text = [[array 
    valueForKeyPath:@"vicinity"]objectAtIndex:indexPath.row];
    NSURL *imgUrl = [NSURL URLWithString:[[array 
    valueForKey:@"icon"]objectAtIndex:indexPath.row]];
    NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
    cell.imageView.layer.cornerRadius =        
     cell.imageView.frame.size.width/2;
    cell.imageView.layer.masksToBounds = YES;
    cell.imageView.image = [UIImage imageWithData:imgData];
    
    return cell;
     }
    

    #import.h

    @interface JsonViewController :     
    UIViewController<UITableViewDelegate,UITableViewDataSource>
    @property (weak, nonatomic) IBOutlet UITableView *jsonTableview;
    @property (weak, nonatomic) IBOutlet UIBarButtonItem *barButton;
    @property (strong,nonatomic)NSArray *array;
    @property NSInteger select;
    
    0 讨论(0)
  • 2020-12-05 17:18

    RESPONSE contains an array not an object.

    So try like this:

    NSMutableArray *response = [json valueForKey:@"RESPONSE"];
    NSString *username = [[response objectAtIndex:0] valueForKey:@"username"];
    NSString *emailId  = [[response objectAtIndex:0] valueForKey:@"email"];
    NSLog(@"User=>[%@] Pwd=>[%@]",username ,emailId );
    
    0 讨论(0)
  • 2020-12-05 17:23

    1)Sequence of keys (or nodes) (MESSAGE, RESPONSE and STATUS) is changed as compared to web response above.

    The NSLog of NSDictionary is based on the sorted keys.

    2)The RESPONSE is get enclosed in '(' & ')' braces.

    RESPONSE =(
                {
            email = "abc@gmail.com";
            id = 20;
            location = "31.000,71.000";
            phone = 1234567890;
            username = john;
        }
    );
    

    The RESPONSE is a key and the value is an NSArray. The array contains one NSDictionary object with keys as email, id, location, phone and username.

    NOTE: () says array. {} says dictionary.

    0 讨论(0)
  • 2020-12-05 17:28

    First of all in your JSON response dictionary, under the key 'RESPONSE' you have a array not a dictionary and that array contains dictionary object. So to extract username and email ID so as below

    NSMutableDictionary *response = [[[json valueForKey:@"RESPONSE"] objectAtIndex:0]mutableCopy];
     NSString *username = [response valueForKey:@"username"];
     NSString *emailId = [response valueForKey:@"email"];
    
    0 讨论(0)
提交回复
热议问题