JSON parsing using NSJSONSerialization in iOS

≡放荡痞女 提交于 2019-11-27 20:54:48

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

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.

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.

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

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;

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!