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);
1
  • 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. Commented Dec 23, 2013 at 20:25

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

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

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

myOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];

Comments

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.

3 Comments

The user stated that they are using AFNetworking 2. AFJSONRequestOperation is no longer available.
AFJSONRequestOperation is deprecated in Latest Version of AFNetworking. So what we can use in place of AFJSONRequestOperation @zorayr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.