Friday, October 12, 2012

Parse JSON data in Objective C (iOS 5)

Hello,

Recently I was working on native iPAD app where we were having certain APIs which returns JSON data. This blog is about parsing JSON data in Objective C.

Following is the code to send request.


NSString *serviceURI = @"http://myapiturl.com";
    serviceURI = [serviceURI stringByAppendingString:sort];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:serviceURI]];
    [request setHTTPMethod:@"GET"];
    NSString *contentType = [NSString stringWithFormat:@"application/json"];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField: @"Accept"];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        NSURLResponse *response = nil;
        NSError *error = nil;
        
        NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
                                                     returningResponse:&response
                                                                 error:&error];
        if(receivedData==nil){
            [SerenaNotifications showNetworkNotifcations];
        }else{
        }
});

Please note that here we are using GCD (grand central dispatch) I will explain this in other blog post. We will get our JSON data in receivedData variable. iOS 5 gives native classes for JSON serialization. Following code will go in else loop.

NSError *myError = nil;
            NSDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];
            NSArray *resultArray = [res objectForKey:@"results"];

Normally in JSON request, results are added with results key. In your case if key is different, replace it in place of results.

This will give you all the results. If you have a single value in key you can access it as follow.

NSString* value = [object valueForKey:@"key"];

If you want to convert it to integer value. Use following code.

NSInteger intValue = [[object valueForKey:@"value"] intValue];



If you want to convert it to boolean value, use following code.

bool boolValue = [[object valueForKey:@"value"] boolValue];

Now you have all the results in resultArray. How to iterate through it and get a single object? Check the following code.

 NSEnumerator *e = [resultArray objectEnumerator];
            
            NSDictionary *object;
            while (object = [e nextObject]) {
             }

Object is the NSDictionary object having your single result object. Again you can use objectForKey and valueForKey methods of NSDictionary class in case you have nested JSON structure.

Hope this post helps you.





No comments:

Post a Comment