user3741418
user3741418

Reputation: 439

Parsing JSON with AFNetworking into NSDictionary

I am trying to parse some JSON with AFNetworking and an NSDictionary. However something seems strange with the JSON. The JSON contains routes for shuttles, but I do not see a 'route' in the JSON.

When I run this code I get an empty NSDictionary with 15 allocated spaces.

NSString *methodURL = [NSString stringWithFormat:@"%@GetRoutesForMapWithSchedule", BASE_URL];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:methodURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    _routes = (NSDictionary *)responseObject;
    //_route = _routes[@"Stops"];

    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Can anyone explain how I can get all the info for one route? This is the JSON.

    NSArray *routes = (NSArray *)responseObject;

    NSDictionary *oneRoute = responseObject[0];
    NSDictionary *stops = oneRoute[@"Stops"];

Upvotes: 0

Views: 1486

Answers (1)

Dima
Dima

Reputation: 23624

The problem is that the top level JSON object is actually an array, not a dictionary as you're trying to cast it to. Each element of the array on the other hand, is a dictionary.

Here is some code to get the general data structure and to get a piece of data out of one of the routes.

NSArray *routes = (NSArray *)responseObject;

NSDictionary *firstRoute = responseObject[0];
NSString *description = firstRoute[@"Description"];

Edit: To parse Stops, you would do something like this:

NSArray *stops = firstRoute[@"Stops"];
NSDictionary *firstStop = stops[0];
NSString *stopDescription = firstStop[@"Description"];

Upvotes: 1

Related Questions