JSON parsing using NSJSONSerialization in iOS

I am parsing JSON in my code. But I get some unexpected problems while retrieving the parsed JSON data. So let me explain my problem.

I need to JSON following JSON data using xcode. This is what parses the data when I delete the same URL in the 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 achieve this JSON data is as follows:

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

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

 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 noticed two things:

  • The sequence of keys (or nodes) ( MESSAGE , RESPONSE and STATUS ) changes compared to the web response above.

  • RESPONSE enclosed in brackets '(' & ')' .

Now, if I highlighted the values ​​for the keys MESSAGE and STATUS and NSLog them, then they will be printed as the correct line.

Like msgStr:Here will be message and Status:OK

But , if I highlight the value for RESPONSE as a dictionary and again separating the sub-settings of this dictionary, such as email and username , then I can not get these as a string .

Here is the code 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 do not print as a normal string , instead they are displayed as:

 username:( john ) email:( abc@gmail.com ) 

So my question is why it doesn't work like a normal string? If I tried to use these variables further, they displayed the value enclosed in '(' & ')' curly braces. Is this due to NSJSONSerialization ?

+6
source share
6 answers

First of all, in your JSON dictionary answer, under the key < RESPONSE "you have an array, not a dictionary , and this array contains a dictionary object. Thus, to extract the username and email address as shown below

 NSMutableDictionary *response = [[[json valueForKey:@"RESPONSE"] objectAtIndex:0]mutableCopy]; NSString *username = [response valueForKey:@"username"]; NSString *emailId = [response valueForKey:@"email"]; 
+7
source

When you see braces, it means an array, not a dictionary. Your JSON also shows that by bracketing the data ('[' 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 over the array:

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

or grab a dictionary by index:

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

If in doubt, enter the class:

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

to find out what is coming back from the dictionary.

+4
source

1) The key sequence (or nodes) (MESSAGE, RESPONSE and STATUS) is changed compared to the web response above.

NSLog NSDictionary based on sorted keys.

2) RESPONSE are enclosed in braces ('and') '.

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

RESPONSE is the key, and the value is NSArray . The array contains one NSDictionary object with keys like email address, identifier, location, phone and username.

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

+3
source

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 ); 
+2
source

pragma sign - availability and score check

 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
source

By serializing the data, you get a json object. Json object and dictionary are slightly different.

Instead of using:

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

using:

 NSDictionary *json = (NSDictionary*) data; 
-2
source

Source: https://habr.com/ru/post/959378/


All Articles