Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

Parsing a JSON Response from the Cloud

Part of the iOS Cloud Development For Dummies Cheat Sheet

When you use a web service that's based in the cloud, your response might be in JSON. If, when working with your cloud-based web service, you were to enter the following in your web browser

http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=Empire 
State Building&

you'd get back some JSON — the following, for example

result {
results: [
  {
   …
   geometry {{
      bounds: {
       northeast: {
       lat: 40.7489545,
       lng: -73.98483449999999
       },
       southwest: {
       lat: 40.7479245,
       lng: -73.9865073
                         }
       },
     location: {
       lat: 40.7484395,
       lng: -73.9856709
  },
…
           }

Since JSON is just as cryptic as XML, you would then have to parse whatever it is that JSON gives you.

Parsing JSON, however, is quite different from parsing XML. JSON is built upon two structures you are quiet familiar with — arrays and dictionaries. The following JSON example uses both:

NSError *error = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data 
options:NSJSONReadingMutableContainers error:&error];

When you do the JSON parsing, you have few options you can set as well:

  • NSJSONReadingMutableContainers: The arrays and dictionaries you get back are mutable so you can modify them. The default is immutable.

  • NSJSONReadingMutableLeaves: The strings you get back are mutable so you can modify them. The default is immutable.

  • NSJSONReadingAllowFragments: Specifies that the parser should allow top-level objects that are not arrays or dictionaries. The default requires the JSON top-level objects to be either an arrays or dictionaries.

When you use the NSJSONSerialization class, you (usually but not necessarily) get back either an array or dictionary that can include strings and numbers and even other arrays and dictionaries (think property list objects here).

In this case, you could get at the location lat and lng by doing

NSDictionary *result = [results objectAtIndex:0];
NSDictionary *geometry = [result objectForKey:@"geometry"];
NSDictionary *location = [geometry objectForKey:@"location"];
latitude = [location valueForKey:@"lat"];
longitude  = [location valueForKey:@"lng"];
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!