Site icon MobileSiri

How To Fetch and Parse JSON Data — iOS Development

In Previous Tutorials, Tutorial 4 and in Tutorial 5 when we need data we created out local NSArray and accessed it. But mostly in real life application, your data would be on some server and you would access it through web service it can be JSON,SOAP or XML. So, now we will do a little demo about getting data from a Web Service in JSON format. Again I am hoping that as we already have discussed good amount objective C stuff so I would not explain stuff in detail.

Getting Data From Web Services in JSON Format:

Go ahead and create a new Project name it HotelData. In Storyboard delete your default ViewController class and also delete your Default View Controller in the storyboard. Drag a new TableViewController from Utility area into your
storyboard. Then create a new Objective Class whose subclass should be UITableViewController and name this class HotelViewController. Now assign your HotelViewController Class to your TableViewController in StoryBoard.
Again create a new class whose subclass would be UITableViewCell and name it HotelCell. As this class is inherited from UITableViewCell you would use it to create your custom cell with your custom view and data items in it.

Now go back to your storyboard and add four UILabel inside your Table View Cell as shown below;

After doing this select your TabelViewCell name its identifier as “Cell” and assign it custom class HotelCell. After that, Open HotelCell and storyboard in a split view and from your TableView Cell create outlets for each of your UILabel after that in the header file of your HotelCell would have these properties.

#import <UIKit/UIKit.h>
@interface HotelCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *lblID;
@property (weak, nonatomic) IBOutlet UILabel *lblName;
@property (weak, nonatomic) IBOutlet UILabel *lblCity;
@property (weak, nonatomic) IBOutlet UILabel *lblAddress;
@end

Now have a look at the JSON that we will work on. Open this URL see what kind of data it contains.

Read More: Working with UIScrollView, UITextField, and UIPickerView in iOS

Fetch and Parse JSON Data

If you have seen this JSON data carefully that your would have noticed it contains data about different Hotels. Its entities are ID , Hotel Name , City , Address ,Phone No and its latitude & longitude.Below is one of the nodes in this service.

"id": "3",
"name": "Pearl Continental",
"city": "Karachi",
"address": "Club Road, Karachi",
"locationLong": "67.0250505",
"locationLat": "24.8475524",
"phone": "+9221111505505"

Although from web service we can directly access this data in NSArray or NSDictionary but it proves more useful if first,we create a Model class our Data so currently, we will only create a model class for Id,name,city and address but you can add more properties if you want.
So, create a new class whose subclass is NSObject and name this class HotelObject. Below is the code of header file of this class.

#import <Foundation/Foundation.h>
@interface HotelObject : NSObject
-(instancetype)initWithId:(int)Id Name:(NSString *)currentName City:(NSString
*)givenCity Address:(NSString *)givenAddress;
@property (nonatomic) int Id;
@property (nonatomic,strong) NSString * city;
@property (nonatomic,strong) NSString * name;
@property (nonatomic,strong) NSString *address;
@end

And here is the code for Implementation file of HotelObject Class.

#import "HotelObject.h"
@implementation HotelObject
-(instancetype)initWithId:(int)Id Name:(NSString *)currentName City:(NSString
*)givenCity Address:(NSString *)givenAddress{
self = [super init];
if(self){
self.Id = Id;
self.name = currentName;
self.city = givenCity;
self.address = givenAddress;
}
return self;
}
@end

Now Coming back to your HotelViewController class add a constant which holds the URL of your service add it on the top of your class as shown below.

#define JSON_URL @"http://merrycode.com/belly/json/places.php"

Import HotelObject and HotelCell class in your implementation class header.

#import "HotelObject.h"
#import "HotelCell.h"

Make a property which will hold all object of your HotelCell class.
@property (nonatomic,strong) NSMutableArray *objectHolderArray;
Also, implement the getter of objectHolderArray.In this getter, we will check if the object is instantiated if not we will do that.

-(NSMutableArray *)objectHolderArray{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}

Clear the comments of the TableViewController Delegate class which we will not be using here and go ahead and implement the TableViewDelegate methods as shown below. We have done this before so it does need much explanation.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [self.objectHolderArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
HotelCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
HotelObject *currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.row];
cell.lblID.text = [NSString stringWithFormat:@"%d",currentHotel.Id];
cell.lblName.text = currentHotel.name;
cell.lblCity.text = currentHotel.city;
cell.lblAddress.text = currentHotel.address;
return cell;
}

Now in ViewDidLoad we will do the important stuff for this application. Here we will call the service and parse it according to our need. Fist we create NSURL object which holds our service URL that we will hit to get the
data.

NSURL *blogURL = [NSURL URLWithString:JSON_URL];

Then we create NSData object which holds the data which we fetch from the URL.

NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];

We create NSError object for if our JSON is not correct to be parsed.

NSError *error = nil;

Now, we create a Dictionary object which gets data from NSJSONSerialization method. And it is parsed successfully it will not hold JSON data from our web service.

NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];

Now to access every node of our data we would need to perform iteration.

for (NSDictionary *bpDictionary in dataDictionary)

And in every iteration bpDictionary would contain data for next node.And from each node, we can access data by its key so inside code we create a HotelObject object and then add it to our objectHolder Array which is data source of our TableView. Below is the code which is inside the loop.

HotelObject *currenHotel = [[HotelObject alloc]initWithId:[[bpDictionary
objectForKey:@"id"]integerValue] Name:[bpDictionary objectForKey:@"name"]
City:[bpDictionary objectForKey:@"city"] Address:[bpDictionary
objectForKey:@"address"]];
[self.objectHolderArray addObject:currenHotel];

And now when your run the app you see TableView filled like shown below;

Again Here is the complete code of your HotelViewController.

#define JSON_URL @"http://merrycode.com/belly/json/places.php"
#import "HotelViewController.h"
#import "HotelObject.h"
#import "HotelCell.h"
@interface HotelViewController ()
@property (nonatomic,strong) NSMutableArray *objectHolderArray;
@end
@implementation HotelViewController
- (void)viewDidLoad
{
NSURL *blogURL = [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
for (NSDictionary *bpDictionary in dataDictionary) {
HotelObject *currenHotel = [[HotelObject alloc]initWithId:[[bpDictionary
objectForKey:@"id"]integerValue] Name:[bpDictionary objectForKey:@"name"]
City:[bpDictionary objectForKey:@"city"] Address:[bpDictionary
objectForKey:@"address"]];
[self.objectHolderArray addObject:currenHotel];
}
[super viewDidLoad];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [self.objectHolderArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
HotelCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
HotelObject *currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.row];
cell.lblID.text = [NSString stringWithFormat:@"%d",currentHotel.Id];
cell.lblName.text = currentHotel.name;
cell.lblCity.text = currentHotel.city;
cell.lblAddress.text = currentHotel.address;
return cell;
}
-(NSMutableArray *)objectHolderArray{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}
@end

This was the most simple way to access any data from the web and parse JSON. When you look for JSON parsing on the web you would see many different libraries which would help you do parsing like SBJSON library would help you get the data from URL in a different thread.
We have cover basic concepts of Xcode and Object C and this would help you to understand more.

MobileSiri.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. Read about our Affiliates Disclosure Policy here. Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.
Exit mobile version