JSON Parsing Framework and Integration
Following are the parsers that can be used for JSON parsing:
1.) iOS Native parser : With the introduction of iOS 5, Apple introduced native support for parsing JSON with the NSJSON Serialization class. Therefore there’s really no need for third-party libraries (except really in terms of performance in some cases - or if you’re more comfortable with them). It is very simple to use:
1. Firstly, retrieve your JSON data from your web-service as NSData
2. Then, create your JSON dictionary with something like: ⁃ NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
Reference Urls:
http://www.appcoda.com/fetch-parse-json-ios-programming-tutorial/
http://www.raywenderlich.com/5492
http://blog.safaribooksonline.com/2013/03/06/parsing-json-in-objective-c-using-nsjsonserialization/
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
2.) Open Source Libraries:
Ø TouchJSON : TouchJSON is an Objective-C based parser and generator for JSON encoded data. TouchJSON compiles for Mac OS X and iOS devices (currently iPhone, iPad and iPod Touch).
It is based on Jonathan Wight's CocoaJSON code: http://toxicsoftware.com/cocoajson/
Licence: Redistributions of source code must retain the copyright notice, this list of conditions and the disclaimer.
Reference Urls:
https://github.com/TouchCode/TouchJSON
https://github.com/twoism/iphone-json-example
Ø JSONKit : The fastest performing JSON parser for objective-c by a considerable margin However, there are a couple of limitations that come with it, these are:
Not ARC support.
JSON being parsed must be encoded as Unicode.
That being the case, it is very simple to set-up and use, follow these steps:
1. Download the repository from the URL above.
2. Add the JSONKit .h & .m files to your project.
3. Add the appropriate #import statements to the classes that need it.
4. You can create a dictionary with a line similar to:
o NSDictionary *deserializedData = [jsonString objectFromJSONString]; And, if your dictionary contains an array, you can use a line like:
o NSArray *resultList = [deserializedData objectForKey:@"ResultList"];
Licence : Redistributions of source code must retain the copyright notice, this list of conditions and the disclaimer.
Reference Urls:
https://github.com/johnezang/JSONKit
https://github.com/techtraits/jsonkit-example
https://github.com/JoistApp/JSONKit
ØYAJL: A JSON parser with an array of features:
Stream parsing, comments in JSON and better error messages.
Parse directly from NSString or NSData.
Generate JSON from default or custom types.
Properly handles large numeric types.
Document style parser.
Error by exception or out error.
It’s also very easy to install for iOS (Xcode 4):
1. Add the YAJLiOS.framework to your project.
2. In Build Phases, make sure its listed in Link Binary With Libraries, along with: CoreGraphics.framework * Foundation.framework * UIKit.framework 3. In Build Settings: * Under Framework Search Paths make sure the (parent) directory to YAJLiOS.framework is listed. * Under Other Linker Flags in your target, add -ObjC and –all load 4. Import with #import <YAJLiOS/YAJL.h>
YAJL is the next fastest library after native iOS library but it still took twice as long as the native library. It got some issues with ARC also. For apps that must provide legacy support, YAJL is the best choice.
Reference Urls:
http://kevsaidwhat.blogspot.in/2013/04/using-yajl-with-objective-c.html
Ø JSON – framework : JSON (JavaScript Object Notation) is a light-weight data interchange format that's easy to read and write for humans and computers alike. This library implements chunk-based JSON parsing and generation in Objective-C.
It’s also very straight forward to install, simply go to https://github.com/stig/json-framework/, download the repository and follow these steps:
1. In the Finder, navigate to the Classes folder (in the repository).
2. Select all the files and drag-and-drop them into your Xcode project.
3. Tick the Copy items into destination group's folder option.
4. Use #import "SBJson.h" in your source files.
Licence : Redistributions of source code must retain the copyright notice, tis list of conditions and the disclaimer.
Reference Urls :
https://github.com/stig/json-framework
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
How to integrate iOS FrameWork For JSON Parsing?
1.) Create a new Xcode application following your own app architecture
2.) Integrate your Url in App that gives JSON data in response.I have used "@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"
" that will have loan data .
3.) Create Connection and make request with your JSOn Url
4.) In Connection:DidFinishLoading,make a call to your parser class that will parse JSON data(This will be totally depend on you from where you make call to parser class,I made it from Manager ).
Parser Class will have the following code :(This is just an example which I used)
- (id)initWithData:(NSData *)responseData
{
// 1.Now create a NSDictionary from the JSON data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
// 2.Create a new array to hold the loans
NSMutableArray *loans = [[NSMutableArray alloc] init];
//3. Get an array of dictionaries with the key "loans"
NSArray* latestLoans = [jsonDictionary objectForKey:@"loans"];
//4.Iterate through the array of dictionaries
for(NSDictionary *dict in latestLoans)
{
//NSLog(@"Loan :%@",dict);
// 4.1.Create a new loan object for each one and initialise it with information in the dictionary
LoanEntity *loan = [[LoanEntity alloc] initWithJSONDictionary:dict];
//4.2. Add the loan object to the array
[loans addObject:loan];
}
// Return the array of loan objects
return (id)loans;
}
The above code will give me individual loans as a dictionary in an Array of Dict("Loans") for JSON data that looks like this in Url:
"loans":[
{"id":643323,
"name":"Tabitha",
"description":{"languages":["en"]},
"status":"fundraising",
"funded_amount":0,
"basket_amount":0,
"image":{"id":1487041,"template_id":1},
"activity":"Fruits & Vegetables",
"sector":"Food",
"use":" to buy a variety of vegetables, potatoes and tomatoes for sale.",
"location":{"country_code":"KE","country":"Kenya","town":"Msambweni","geo": {"level":"country","pairs":"1 38","type":"point"}},
"partner_id":164,
"posted_date":"2013-12-09T10:50:02Z",
"planned_expiration_date":"2014-02-07T10:50:02Z",
"loan_amount":250,
"borrower_count":1,
"lender_count":0,
"bonus_credit_eligibility":true},
In the above Code,
Loan Entity is an individual NSObject class that will retrieve individual loan data from dictionary and save them in Entity.
See below code this class contains:
// Init the object with information from a dictionary
- (id)initWithJSONDictionary:(NSDictionary *)jsonDictionary
{
if(self = [self init]) {
// Assign all properties with keyed values from the dictionary
_name = [jsonDictionary objectForKey:@"name"];
_sector = [jsonDictionary objectForKey:@"sector"];
_use = [jsonDictionary objectForKey:@"use"];
_activity = [jsonDictionary objectForKey:@"activity"];
_funded_amount =[jsonDictionary objectForKey:@"funded_amount"];
_loan_amount = [jsonDictionary objectForKey:@"loan_amount"];
_country = [[jsonDictionary objectForKey:@"location"] objectForKey:@"country"];
_status = [jsonDictionary objectForKey:@"status"];
}
return self;
}
This Parsed data can now be used on your iOS App.
Note : I have given Loan example to show parsing.Retrieving data in "initWithJSONDictionary" will totally depend on your JSON data and structure they bind up in.
Happy Coding ...!!!!!