如何在Custom tableview中解析JSON响应

时间:2014-06-30 04:26:30

标签: ios objective-c json uitableview ios7

我的JSON结构是

   {"Offer_Stag1":
   [{
   "Area":"1200م2",
   "HotlineNumber1":"12345678",
   "HotlineNumber2":"12345678",
   "Image":"almithaq.mawaqaademo.com\/AlMithaqOfferThumbImages\/19d92aa8-fbc7-49fc-9ebe-a4bdc641216b.jpg",
   "LargeImage":"almithaq.mawaqaademo.com\/AlMithaqOfferThumbImages\/81ecfc05-8431-4ce7-8ac9-5e93c24d7deb.jpg",
   "SectionNo":"184","Stage":"Stage1",
   "TheDetails":"موقع مميز، على مدخل المرحلة الاولى، قريبة من الخدمات\u0009","TheView":" البحرية 17 متر"
    },
    {"Area":"1205م2 – 1201م2",
    "HotlineNumber1":"12345678",
    "HotlineNumber2":"12345678",
    "Image":"almithaq.mawaqaademo.com\/AlMithaqOfferThumbImages\/9cdcab19-49f8-4ad8-a42c-f5e9df273320.jpg",
    "LargeImage":"almithaq.mawaqaademo.com\/AlMithaqOfferThumbImages\/bca29ff9-e6f3-4554-8a8c-9f685ceb9ba6.jpg",
    "SectionNo":"581-582",
    "Stage":"Stage1",
    "TheDetails":"أرضين متلاصقتين، سكة جانبية","TheView":"البحرية 16 متر"
   }]
   }

我有自定义表格单元格想要解析它,把我赶出去。

先谢谢。

3 个答案:

答案 0 :(得分:0)

尝试做这样的事情。这不是确切的解决方案,您必须以自己的方式解决。

NSString *link =  [NSString stringWithFormat:@"yourServiceURL"];
    NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:encdLink];
    NSData *response = [NSData dataWithContentsOfURL:url];
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];

现在,您已将数据存储在数组中,并使用objectForKey或valueForKey将其解压缩。您可以根据需要使用NSDictionaryNSArray

这就是我正在从JSON获取图像并在我的应用程序中显示的内容。首先从上面的代码中获取数组。然后提取出像这样的图像内容:

_demoArray = [json valueForKey:@"yourKeyField"];

现在你在demoArray中有了值。

希望这有帮助。

答案 1 :(得分:0)

假设您以类似的方式使用JSON array获取AFNetworking

-(void)makeRequest
{           
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.myServer.com"]];  
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //AFNetworking asynchronous url request
    dispatch_group_t group = dispatch_group_create();

    dispatch_group_enter(group);

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        // You parse your JSON array
        NSDictionary *fullResponse = [[NSDictionary alloc] init];
        fullResponse = responseObject;

        if ([[fullResponse objectForKey:@"status"] intValue]  == 1) {
            NSDictionary *successResponse = [[NSDictionary alloc] init];
            successResponse = [fullResponse objectForKey:@"success_response"];

            NSArray *offer_Stag1 = [[Nsarray alloc] init];
            Offer_Stag1 = [successResponse objectForKey:@"Offer_Stag1"];

            allObjects = [[NSMutableArray alloc] init];

            for (int i = 0; i < [offer_Stag1 count]; i++){
                NSDictionnary *singleObject = [offer_Stag1 objectAtIndex:i];
                [allObjects addObject:singleObject];
            }

        dispatch_group_leave(group);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Request Failed: %@, %@", error, error.userInfo);
        dispatch_group_leave(group);
    }];

    [operation start];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{

        // Here you call the desired method after all data have been downloaded, typically you should reload your tableView
        [self.myCustomTableViewWithDataFromServer reloadData];   
    });

}

一些解释:

  • 首先获取服务器
  • 您将JSON object解析为NSDictionnaryNSarray(或两者兼而有之)
  • 您将AFNetworking request封装在一个已发送的群组中,以便在下载完所有数据后重新加载UITableView

然后,我猜你做到了,你可以访问存储数据的NSMutableArray,以便在单元格中显示它们

您的NSMutableArray是一个全局变量:

@interface MyCustomController() {
    NSMutableArray *allObjects;
}

答案 2 :(得分:0)

self.itemshowdetailsAr=[[NSMutableArray alloc] init];

-(void)yourmethodName
{
aray = [[NSArray alloc] init];

NSURL *url = [[NSURL alloc] initWithString:@"yoururlname.php"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"the json resut is %@",JSON);
    aray = [JSON objectForKey:@"Offer_Stag1"];


        for (NSDictionary *tmp in aray) {
        NSMutableDictionary   *itemshowdetails=[[NSMutableDictionary alloc]init];

            [itemshowdetails setValue:[tmp objectForKey:@"Area"] forKey:@"Area"];
            [itemshowdetails setValue:[tmp objectForKey:@"HotlineNumber1"] forKey:@"HotlineNumber1"];
            [itemshowdetails setValue:[tmp objectForKey:@"HotlineNumber2"] forKey:@"HotlineNumber2"];
            [itemshowdetails setValue:[tmp objectForKey:@"TheDetails"] forKey:@"TheDetails"];
            [itemshowdetails setValue:[tmp objectForKey:@"TheView"] forKey:@"TheView"];


            [self.itemshowdetailsAr addObject:itemshowdetails];
        }

    [self.tableView reloadData];  

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];

[operation start];
}


#pragma mark - tablevie data source

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

return [self.itemshowdetailsAr count];

}

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
static NSString *CellIdentifier = @"cell";


UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];




if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;


}



  cell.textLabel.text = [[self.itemshowdetailsAr objectAtIndex:indexPath.row ] objectForKey:@"Area"];

cell.detailTextLabel.text = [[self.itemshowdetailsAr objectAtIndex:indexPath.row ] objectForKey:@"HotlineNumber1"];
 ....
 ....
 .....
return cell;

 }