Parsing JSON in iOS


A lot of APIs will give you responses in JSON format. Here we'll review JSON parsing in iOS so that you can get to the interesting data faster.

This tutorial assumes that you've already gone through our iOS getting started tutorial and are familiar with how our iOS SDK works. Although we use the output from our YouTube ListSearchResults Choreo in this tutorial, the same steps we outline here will work for parsing any JSON in iOS.

Get JSON output

1 Log in to Temboo and go to the YouTube > Search > ListSearchResults Choreo in our Library.

2 Enter any search term you want for the Query input and click Generate Code to test the Choreo from our website.

3 You get a whole bunch of JSON in the Response output. These are the results of the search. Next we'll see how to parse through this response in iOS and pick out only the pieces we're interested in.

Parse it in iOS

4 Create a new OS X > Application > Command Line Tool project in Xcode. Make sure to add the core directory from the Temboo iOS SDK and the TMBYoutTube.h and TMBYouTube.m files as described in our getting started tutorial.

5 Copy the code below into your main.m class, between the Foundation.h import statement and the main method. Steps 7 - 9 talk you through what happens in the code.

#import "TMBYouTube.h"
#import "TMBChoreography.h"
#import "TMBTembooSession.h"

@interface ListSearchResults : NSObject <TMBChoreographyDelegate>
-(void)runListSearchResultsChoreo;
-(void)choreographyDidFailWithError:(NSError*)error;
-(void)choreographyDidFinishExecuting:(TMBYouTube_Search_ListSearchResults_ResultSet*)result;
@end

@implementation ListSearchResults

-(void)runListSearchResultsChoreo {
	// Instantiate the Choreo, using a previously instantiated TembooSession object, eg:
	TMBTembooSession *session = [[TMBTembooSession alloc] initWithAccount:@"ACCOUNT_NAME" appKeyName:@"APP_NAME" andAppKeyValue:@"APP_KEY"];
	
	// Create the choreo object using your Temboo session
	TMBYouTube_Search_ListSearchResults *listSearchResultsChoreo = [[TMBYouTube_Search_ListSearchResults alloc] initWithSession:session];
	
	// Get Inputs object for the choreo
	TMBYouTube_Search_ListSearchResults_Inputs *listSearchResultsInputs = [listSearchResultsChoreo newInputSet];
    
	// Set inputs
	[listSearchResultsInputs setQuery:@"goats yelling like humans"];
    
	// Execute choreo specifying this class as the choreo delegate
	[listSearchResultsChoreo executeWithInputs:listSearchResultsInputs delegate:self];
}

// TMBChoreographyDelegate method implementation - handle choreo errors
-(void)choreographyDidFailWithError:(NSError*)error {
	// Log error to the console
	NSLog(@"Error - %@", error);
}

// TMBChoreographyDelegate method implementation - choreo executed successfully
-(void)choreographyDidFinishExecuting:(TMBYouTube_Search_ListSearchResults_ResultSet*)result {
	// Grab the response and convert to NSData in preparation for parsing
    NSData *jsonData = [[result getResponse] dataUsingEncoding:NSUTF8StringEncoding];
    
    // Handle errors parsing if any
    NSError *parsingError = nil;
    
    // Parse search results JSON into object
    NSMutableDictionary *searchResults = [NSJSONSerialization
                                          JSONObjectWithData:jsonData
                                          options:NSJSONReadingMutableContainers
                                          error:&parsingError];
    
    // Grab the first item in the 'items' array
	NSArray *items = searchResults[@"items"];
	NSObject *item = items[0];
    
    // Extract the snippet
    NSObject *snippet = [item valueForKey:@"snippet"];
    
    // Log title and description
    NSLog(@"Title: %@", [snippet valueForKey:@"title"]);
    NSLog(@"Description: %@", [snippet valueForKey:@"description"]);
}

@end

6 Update your main method to run the Choreo:

int main(int argc, const char * argv[]){
    @autoreleasepool {
        ListSearchResults *tutorial = [[ListSearchResults alloc] init];
        [tutorial runListSearchResultsChoreo];
        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}

7First we converted the JSON text from the response to an iOS dictionary using NSJSONSerialization.

8Next, we parsed out the piece of data we want from the JSON. It helps to look at the JSON string's structure to get an idea of how it is organized. The two main elements you should look for are:

Class nameHow it appears in the JSON string
NSArray"name": [
NSObject"name": {

For these results, we wanted the title of the first video in the search results. We got the items array, then the first item in that array (at index 0). Then we wanted the snippet object within the first item in the array. We used the getJSONArray and getJSONObject methods for this. In other words:

Method nameDescription
searchResults[@"items"]The array of videos in the search results
items[0]The first video within those results
[item valueForKey:@"snippet"]The snippet containing descriptive details of each video

9To finish up, we parsed the title property from the snippet object using the valueForKey method.

10All Finished! Run the code in Xcode to try it out. You should see the title and description of your first YouTube Search result in the console.

What next?

Now you should be to able to parse all sorts of JSON responses with our iOS SDK. Check out the 2000+ Choreos in our Library and find some exciting data to parse.

Once you've got your code up and running, you're ready to move on and do more. From monitoring your running applications, to moving your generated Temboo code to your preferred development environment and sharing it with colleagues, collaborators and friends - we've got you covered.

Need help?

We're always happy to help. Just email us at support@temboo.com, and we'll answer your questions.

We're hiring!

Like what we do? Take a look at our open positions.


Back