我正在使用AFNetworking 2.0向我的返回JSON数据的Web服务发出POST请求。
{
post = {
"first_name" = Joe;
"last_name" = Blogs;
"user_id" = 1;
};
},
{
post = {
"first_name" = Bill;
"last_name" = Gates;
"user_id" = 2;
};
}
我能够将responseObject打印到控制台上,显示我的JSON数据。
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);
}];
每个“post”将用于我的View Controller上的表格单元格。我正在努力了解如何使每个帖子成为数组中的对象。任何有用的帮助。
答案 0 :(得分:1)
更新
您可以使用此代码剪切来执行所需的功能:
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];
并在您的CellForRowAtIndexPath
方法中,使用此代码剪切显示您单元格中的数据:
NSDictionary *res=[self.storesArray objectAtIndex:indexPath.row];
cell.firstName.text=[res objectForKey:@"first_name"];
cell.lastName.text=[res objectForKey:@"last_name"];
此NSDictionary
适用于键值对样式,因此您只需提及键名即可获取任意键的值,并获取该键的值。