JSON Response in postPath AFHTTPClient

AFNetworking should instantiate a AFJSONRequestOperation. Probably it creates a basic AFHTTPRequestOperation instead (check [operation class]) resulting in a NSData object as response.

Make sure you register the operation class in the init method of your AFHTTPClient subclass (initWithBaseURL):

[self registerHTTPOperationClass:[AFJSONRequestOperation class]];

// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Accept" value:@"application/json"];

You could also try to use AFJSONRequestOperation directly like this:

NSURLRequest *request = [[objectManager HTTPClient] requestWithMethod:@"POST" path:@"users/login/?format=json" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"JSON: %@", JSON);
} failure:nil];
[[objectManager HTTPClient] enqueueHTTPRequestOperation:operation];

What you are seeing, if I'm not mistaken, is the raw bytes from the NSData that is given to you when your success block is called.

The hex you posted reads:

{"reason": "API Key found", "api_key": "a5fae247f3bd51ad99c8c97468d84cab60e7e8c1", "success": true}

The reason the second NSLog shows you what you want is that the %@ format string calls the description (correct me if I'm wrong here, SO) of the object you pass it and the NSData probably knows it is a string underneath.

So, on to how to get the JSON. It is really rather simple. Once you have your response object, you can do something like this:

NSDictionary* jsonFromData = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];

What this will do for you is use return an NSDictionary which encodes the root object in the JSON and then each value in the dictionary will be of the type NSString, NSNumber, NSArray, NSDictionary, or NSNull. See NSJSONSserialization for documentation.

The NSJSONReadingMutableContainers makes the dictionaries and arrays mutable. It's just a leftover from my code.

Hopefully you're on iOS 5 or later, or you'll need to find another solution for the parsing.


success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSData *responseData = operation.HTTPRequestOperation.responseData;
    id parsedResponse = [RKMIMETypeSerialization objectFromData:responseData    MIMEType:RKMIMETypeJSON error:nil];
    NSString *apiKey = [parsedResponse valueForKey:@"api_key"]
}