0

I am using AFNetworking 2 to grab some json data from a server. It is employee data, and I have made an employee object and an employees NSMutableArray.

My service is working. If I spit out responseObject to the log I get 600 employees. What I am struggling with is how to get those into my employees NSMutableArray.

the responseObject has a type of id, meaning an object with no class, right? I tried to change the id to employee, since that is what I want to return but that didn't work. Then I noticed the responseObject was actually ALL of the objects, so I tried employees but that didn't work.

So I thought I could loop through the objects, but since it isn't really an NSMutableArray I don't understand how.

Any help would be greatly appreciated.

Bryan

- (IBAction)jsonTapped:(id)sender
{

    NSMutableArray *employees;
    employee *thisEmployee  = [employee new];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"XXXXXX" password:@"XXXXXX"];

    AFHTTPRequestOperation *operation = [manager GET: @"https:/XXXXXXXXXXX/something"
                                          parameters: [self jsonDict]
                                             success:^(

                                                       AFHTTPRequestOperation *operation, id responseObject)
    {

                                                       NSLog(@"Submit response data: %@", responseObject);}
                                             failure:^(AFHTTPRequestOperation *operation, NSError *error){
                                               NSLog(@"Error: %@", error);}
                                                   ];
     [operation start];
}

This is inside my success bloc:

   NSMutableArray  *employees = (NSMutableArray *)responseObject;

   NSLog(@"Count of array to begin: %lu", (unsigned long)[employees count]);
   NSLog(@"JSON RESULT %@", responseObject);

   FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
                     [db open];
   for (employee *thisemployee in employees) {
   BOOL success =  [db executeUpdate:@"INSERT INTO employees (firstName,fullName,email) VALUES (?,?,?,?);",thisemployee.firstName,thisemployee.lastName,thisemployee.fullName,thisemployee.emailAddress, nil];
    if (success) {} // Only to remove success error
   NSLog(@"DDD %@", thisemployee);
Bryan Schmiedeler
  • 2,977
  • 6
  • 35
  • 74
  • 1
    The response object will be either an NSArray or an NSDictionary, depending on which the JSON specified. You need to cast it to the correct type to access the data. – Hot Licks Dec 23 '13 at 20:25

3 Answers3

2

You just need to get the responseObject inside the success block and cast it to array, like this:

NSArray *employees = (NSArray *)responseObject;

The AFNetworking already parse the Json for you. What you need to do is just cast to NSArray or NSDictionary, according to your response type (probably an array).

CainaSouza
  • 1,417
  • 2
  • 16
  • 31
  • 1
    I thought this made sense and tried it out, but something is wrong. I cast the responseObject as an employee array (just as you have above), but the values are all just garbage. I iterate through a loop trying to load up my employees one by one so I can write out to a file [I modified my code above], but it crashes every time. – Bryan Schmiedeler Dec 23 '13 at 21:56
2

try setting your operation manager's response serializer to [AFJSONResponseSerializer serializer]

You have your requestSerializer set, not your responseSerializer. (:

myOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
RoHiguera
  • 118
  • 9
0

The trick here is using AFJSONRequestOperation which automatically converts the received response to a NSDictionary or NSArray depending on the returned JSON type. I used the following code for a simple GET request that returned a JSON encoded response:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:SERVER_PATH]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                        path:@"/rank.json"
                                                  parameters:@{@"score" : intToString(highestScore)}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
    rankingReceived([[((NSDictionary *)JSON) objectForKey:@"rank"] intValue]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
{
    rankingReceived(-1);
}];
[operation start];

Request Format (GET): http://server/rank.json?score=x

Response (JSON): "{rank:y}"

Hope this helps!

UPDATE: Seems like AFJSONRequestOperation has been deprecated - I would look at Replacement for AFJSONRequestOperation in AFNetworking 2.x for an alternative.

Community
  • 1
  • 1
Zorayr
  • 23,770
  • 8
  • 136
  • 129
  • The user stated that they are using AFNetworking 2. AFJSONRequestOperation is no longer available. – lordB8r May 21 '14 at 18:47
  • AFJSONRequestOperation is deprecated in Latest Version of AFNetworking. So what we can use in place of AFJSONRequestOperation @zorayr – Rahul Jan 30 '15 at 07:07
  • http://stackoverflow.com/questions/21294178/replacement-for-afjsonrequestoperation-in-afnetworking-2-x – Zorayr Jan 30 '15 at 18:30