Question

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.

I have to parse following JSON data using xcode. This is what data to be parsed looks like while I hit same URL in browser:

{
"RESPONSE":[
    {"id":"20",
    "username":"john",
    "email":"abc@gmail.com",
    "phone":"1234567890",
    "location":"31.000,71.000"}],
"STATUS":"OK",
"MESSAGE":"Here will be message"
}

My code to reach up to this JSON data is as follow:

NSData *data = [NSData dataWithContentsOfURL:finalurl];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

If I print object json using NSLog, i.e. NSLog(@"json: %@", [json description]); it looks like:

json: {
    MESSAGE = "Here will be message";
    RESPONSE =(
                {
            email = "abc@gmail.com";
            id = 20;
            location = "31.000,71.000";
            phone = 1234567890;
            username = john;
        }
    );
    STATUS = OK;
}

So, here I observed two things:

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

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

Now if I separate out values for keys MESSAGE & STATUS and NsLog them, then they get printed as proper string.

Like msgStr:Here will be message & Status:OK

But if I separate out value for RESPONSE as a dictionary and again separating sub values of that dictionary like email and username, then I can't getting those as string.

Here is the code so far I wrote:

NSMutableDictionary *response = [json valueForKey:@"RESPONSE"];
NSString *username = [response valueForKey:@"username"];
NSString *emailId = [response valueForKey:@"email"];

If I print username and emailId, then they are not getting printed as normal string, instead it outputs as:

username:(
    john
)

email:(
    abc@gmail.com
)

So my question is why it's not getting as a normal string? If I tried to use this variables further then they show value enclosed within '(' & ')' braces. Is this happening because of NSJSONSerialization?

Was it helpful?

Solution

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

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top