David Pullar
David Pullar

Reputation: 706

AFNetworking parsing requestObject

I am not sure what is happening but it may be an issue with AFJSONSerializer. Currently I am retrieving JSON data from a URL that returns (in browser):

[{"id": 1, "email": "[email protected]", "password": "123"}, {"id": 2, "email": "[email protected]", "password": "123"}]

I then do a GET request with AFNetworking:

[manager GET:path
    parameters:nil
    success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
        user = [self parseJsonData:responseObject];
    }
    failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

The responseObject returned by the success block always returns:

({"id": 1, "email": "[email protected]", "password": "123"}, ...etc...)

Notice the regular braces instead of square braces. This causes the parse to NSDictionary or NSArray to fail. I can see the objects being returned but I cannot parse them to their respective types. In fact if I attempt the parse to NSDictionary it will show the correct number of objects, all being blank.

Clicking the inspector icon for each index provides me with this error:

[0] = <error: expected ']'
error: 1 errors parsing expression
>

Am I doing something wrong? Any help would be great.

Upvotes: 0

Views: 401

Answers (1)

Rob
Rob

Reputation: 437432

AFNetworking has already parsed the JSON for you (because the manager's default responseSerializer is AFJSONResponseSerializer). You're doing a NSLog of responseObject, which is a NSArray object, not of a JSON string. And when you log a NSArray, it uses the parentheses rather than the square brackets.

If you look at [responseObject class] or [responseObject isKindOfClass:[NSArray class]], you can confirm that responseObject is already been parsed into a NSArray, which you can now use directly.


For example, given that AFNetworking has already parsed the JSON for you, you can now use the resulting object:

NSDictionary *dictionary = responseObject[0];    // get the first dictionary from the array

NSNumber *identifier = dictionary[@"id"];        // this will be @(1)
NSString *email      = dictionary[@"email"];     // this will be @"[email protected]"
NSString *password   = dictionary[@"password"];  // this will be @"123"

Or you can iterate through the array:

for (NSDictionary *dictionary in responseObject) {
    NSNumber *identifier = dictionary[@"id"]; 
    NSString *email      = dictionary[@"email"];
    NSString *password   = dictionary[@"password"];

    NSLog(@"%@; %@; %@", identifier, email, password);
}

Upvotes: 1

Related Questions