user2920762
user2920762

Reputation: 223

AFHTTPRequestOperationManager JSON data to Array

I'm using AFNetworking 2.0 to make a POST request to my web service that returns JSON data.

{
    post =         {
        "first_name" = Joe;
        "last_name" = Blogs;
        "user_id" = 1;
    };
},
    {
    post =         {
        "first_name" = Bill;
        "last_name" = Gates;
        "user_id" = 2;
    };
}

Im able to print out responseObject to the console fine which displays my JSON data.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"user": @"root"};
[manager POST:@"http://192.168.0.100/webservice.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    NSString *responseString = [operation responseString];

    NSError *error;
    NSArray *json = [NSJSONSerialization
                     JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding]
                     options:kNilOptions
                     error:&error];

    for (NSDictionary *dictionary in json)
    {
        NSString *firstName = [[dictionary objectForKey:@"post"] valueForKey:@"first_name"];
        NSLog(@"%@", firstName);
        NSString *lastName = [[dictionary objectForKey:@"post"] valueForKey:@"last_name"];
        NSLog(@"%@", lastName);
    }

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

Each "post" is going to be used for a table cell on my View Controller. Im struggling to understand how to make each post an object in an array. Any help appriciated.

Upvotes: 0

Views: 2657

Answers (1)

Shabir jan
Shabir jan

Reputation: 2427

UPDATE

You can use this code snipped to perform your desired functionality:

        NSString *responseString = [operation responseString];
        NSData *data= [responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error;
        NSArray* results = [NSJSONSerialization JSONObjectWithData:data
                                                       options:0
                                                         error:&error];
             for (int i=0; i<results.count; i++)
             {
                 NSDictionary *res=[results objectAtIndex:i];
                 NSDictionary *res2=[res objectForKey:@"post"];
                 [self.storesArray addObject:res2];

             }
             [self.tableView reloadData];

and in your CellForRowAtIndexPath method, use this code snipped to show data on your cell:

NSDictionary *res=[self.storesArray objectAtIndex:indexPath.row];
cell.firstName.text=[res objectForKey:@"first_name"];
cell.lastName.text=[res objectForKey:@"last_name"];

This NSDictionary works in key values pair style, so you can get the value of any key by just mentioning the key name and get the values of that key.

Upvotes: 1

Related Questions