This post will show how to parse the JSON response received from a web service into an
NSDictionary object. For the purpose of this post, I’ll use a sample web service hosted by jsontest.com that returns the MD5 hash of the entered sample text.
The URL of the sample web service is http://md5.jsontest.com/?text=AmoghNatu.
The output when a request is made to the above URL is as shown below:
In the sample project, I’ll display the MD5 text in an alert box.
For parsing the response JSON, we use the
JSONObjectWithData method. When a request is posted to the web service, the response is initially stored in an
NSData object. This
NSData object is passed to
JSONObjectWithData method as parameter along with json reading options and an error object, in case there is an error while parsing the JSON.
Let’s have a look at the code.
- (NSDictionary *)parseJsonResponse:(NSString *)urlString
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error:&error];
NSLog(@"Download Error: %@", error.localizedDescription);
UIAlertView *alert =
message:[NSString stringWithFormat:@"Error : %@",error.localizedDescription]
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: data
parseJsonResponse is a sample method that I have written that makes a request to the web service and gets the response in JSON. This JSON is then parsed into an
I have uploaded a sample application. The same can be downloaded from here too. Check that if required.
Hope this helps!