How to iterate through a simple JSON object in Objective-C?
json, nsjsonserialization, objective-c
Solution
The top-level object your JSON object is a dictionary, not an array, as indicated by the curly braces. If you are not sure whether you are going to get an array or a dictionary back, you can do some safety checking like this:
// Construct a collection object around the Data from the response
id collection = [NSJSONSerialization JSONObjectWithData:urlData
options:0
error:&error];
if ( collection ) {
if ( [collection isKindOfClass:[NSDictionary class]] ) {
// do dictionary things
for ( NSString *key in [collection allKeys] ) {
NSLog(@"%@: %@", key, collection[key]);
}
}
else if ( [collection isKindOfClass:[NSArray class]] ) {
// do array things
for ( id object in collection ) {
NSLog(@"%@", object);
}
}
}
else {
NSLog(@"Error serializing JSON: %@", error);
}
Problem
I'm very new to Objective-C, I'm a hardcore Java and Python veteran. I've created an Objective-C script that calls a URL and gets the JSON object returned by the URL: ``` // Prepare the link that is going to be used on the GET request NSURL * url = [[NSURL alloc] initWithString:@"http://domfa.de/google_nice/-122x1561692/37x4451198/"]; // Prepare the request object NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30]; // Prepare the variables for the JSON response NSData *urlData; NSURLResponse *response; NSError *error; // Make synchronous request urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; // Construct a Array around the Data from the response NSArray* object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error]; //NSLog(object); // Iterate through the object and print desired results ``` I've gotten this far: ``` NSString* myString = [@([object count]) stringValue]; NSLog(myString); ``` Which returns the size of this array, but how can I loop through this JSON object and print each element? Here's the JSON I'm loading: ``` { "country": "United States", "sublocality_level_1": "", "neighborhood": "University South", "administrative_area_level_2": "Santa Clara County", "administrative_area_level_1": "California", "locality": "City of Palo Alto", "administrative_area_level_3": "", "sublocality_level_2": "", "sublocality_level_3": "", "sublocality":"" } ```