|

Parsing JSON in Objective-C using NSJSONSerialization

JSON is an easy standard to parse in client-server applications. It is easy to implement and simple to understand. With the release of the iOS 5 SDK, the NSJSONSerialization class was added in the SDK, which gives an easy to use delegate method, lifecycle, to parse JSON data.

The following post explains an easy example that fetches the twitter stream of a user (In this example I have fetched my own twitter stream: twitter.com/jadoon88) in a JSON format, and then parses the statuses and NSLogs them.

Start up XCode and create a new iOS application. If you are new to working with XCode, read Your First Objective-C Program in Learning Objective-C 2.0 by Robert Clair. In the implementation file, inside viewDidLoad method, write the following code:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:@"http://api.twitter.com/1/statuses/user_timeline.json?
screen_name=jadoon88"]];

The code above prepares the HTTP web request to a URL that returns a twitter stream in JSON format.

Next, in the same method, we will write code to perform the request and get a JSON response as NSData object. Add the following code below the code from above.

NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];

Next, we will do the magic of serializing JSON. The following code fetches the JSON data in NSData object and serializes to an array. Add this code to the code above in the viewDidLoad method:

NSError *jsonParsingError = nil;
NSArray *publicTimeline = [NSJSONSerialization JSONObjectWithData:response
options:0 error:&jsonParsingError];

Next, just create an NSDictionary object that will store the twitter statuses. Add the following line of code where you have written the code above.

NSDictionary *tweet;

Now, we will iterate the elements in the array, filter out the “text” element in JSON data (that stores the twitter statuses) and NSLog it. The following code does the job:

for(int i=0; i<[publicTimeline count];i++)
{
	tweet= [publicTimeline objectAtIndex:i];
	NSLog(@”Statuses: %@”, [tweet objectForKey:@"text"]);
}

Take a look at the Objective-C Programming Fundamentals LiveLessons video by Jiva Devoe for key concepts and fundamentals of the Objective-C language.

Safari Books Online has the content you need

Check out these Objective-C books available from Safari Books Online:

Programming in Objective-C is a concise, carefully written tutorial on the basics of Objective-C and object-oriented programming for Apple’s iOS and OS X platforms. The book makes no assumptions about prior experience with object-oriented programming languages or with the C language (which Objective-C is based upon). Because of this, both beginners and experienced programmers alike can use this book to quickly and effectively learn the fundamentals of Objective-C. Readers can also learn the concepts of object-oriented programming without having to first learn all of the intricacies of the underlying C programming language.
As iOS apps become increasingly complex and business-critical, iOS developers must ensure consistently superior code quality. This means adopting best practices for creating and testing iOS apps. Test-Driven Development (TDD) is one of the most powerful of these best practices. Test-Driven iOS Development is the first book 100% focused on helping you successfully implement TDD and unit testing in an iOS environment.
Foundation iPhone App Development: Build An iPhone App in 5 Days with iOS 6 SDK quickly enables existing programmers to become familiar and comfortable coding Objective-C using Xcode 4.5, Storyboarding and the iOS 6 SDK to create apps for the iPhone. Nick Kuh, an experienced, Apple award-winning developer, will teach readers how to build an iOS 6 iPhone app from start to finish in 5 days.
HTML5 Canvas Cookbook begins by covering the basics of the HTML5 Canvas API and then provides techniques for handling features not directly supported by the API such as animations and canvas interactivity. It winds up by providing detailed templates for a few of the most common HTML5 canvas application.
If you’re a web developer looking to use this new version of HTML, you might be wondering how much has really changed. Head First HTML5 Programming introduces the key features — including improved text elements, audio and video tags, geolocation, and the Canvas drawing surface — and uses concrete examples and exercises to apply and reinforce these concepts.
In these video LiveLessons, Jiva Devoe helps the viewer understand the key concepts and fundamentals of the Objective-C language. Objective-C Programming Fundamentals LiveLessons (Video Training) covers basic objective-c syntax, objects, memory management, protocols, the foundation framework and errors. The newest features in Objective-C such as ARC, blocks, and properties are included. After watching this video, viewers should be able to build and run basic Objective-c programs.

About the author

Umair Khan Jadoon is an avid developer. He enjoys building awesome apps for mobile and web and occasionally writing about technology. Geek at heart, he’s working on establishing his own mobile app startup.

About Safari Books Online

Safari Books Online is an online learning library that provides access to thousands of technical, engineering, business, and digital media books and training videos. Get the latest information on topics like Windows 8, Android Development, iOS Development, Cloud Computing, HTML5, and so much more – sometimes even before the book is published or on bookshelves. Learn something new today with a free subscription to Safari Books Online.
|

Comments are closed.