如何获取数组中的嵌套json数据并显示在表视图中?

问题描述:

我JSON这样 {
“状态”: “成功”, “代码”: “200”, “menudetails”:{
“menu_id”: “1001”, “菜单名称”:”多彩塔利”, “价格”: “$ 200.00”, “面包”:{
“最大”: “1”, “10”: “Akki rotti”, “11”: “SEL烤肉” } , “rice”:{
“max”:“1”, “14”:“Jeera rice”, “15”:“Biryani”, “16”:“Fried饭” }, “Vegitable”:{
“最大”: “2”, “20”: “梅莱科夫塔”, “21”: “夏希芝士”, “22”: “PALAK芝士” , “23”: “芝士做piaza” } }, “消息”: “Tranasction列表”, “说明”: “Tranasction列表” } 我尝试调用此API如何获取数组中的嵌套json数据并显示在表视图中?

- (void)callApi {

[SVProgressHUD showWithStatus:nil maskType:SVProgressHUDMaskTypeGradient]; 

NSMutableDictionary *finaljson = [NSMutableDictionary dictionary]; 

NSMutableDictionary *postParams = [NSMutableDictionary dictionary]; 
[postParams setObject:[NSNumber numberWithInt:kresto_id] forKey:@"resto_id"]; 
AppDelegate*apDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate]; 


[postParams setObject:apDelegate.subCategoryID forKey:@"menu_id"]; 
NSMutableArray * arrjson = [NSMutableArray array]; 
[arrjson addObject:postParams]; 
[finaljson setObject:arrjson forKey:@"Data"]; 
//NSLog(@"Each time Signup postParam is = %@",finaljson); 

NSError *error = nil; 
NSData *postData = [NSJSONSerialization dataWithJSONObject:finaljson 
                options:kNilOptions 
                error:&error]; 
NSURL *url_request = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseURL,kThaliDetail]]; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url_request 
                 cachePolicy:NSURLRequestUseProtocolCachePolicy 
                timeoutInterval:60.0]; 


// HEADER...STARTS HERE . 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:postData]; 

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) { 

    if (error == nil) { // success.... 

     NSError *jsonError; 
     id response = [NSJSONSerialization JSONObjectWithData:data 
                 options:kNilOptions 
                 error:&jsonError]; 




     // get object after successful retrieving data !!!! 
     dispatch_async(dispatch_get_main_queue(), ^{ 

      [SVProgressHUD dismiss]; 

      NSLog(@"output for Bussiness owner Login:%@",response); 

      NSString* strStatus = [NSString stringWithFormat:@"%@",[response valueForKey:@"status"]]; 
      if ([strStatus isEqualToString:@"Success"]) 
      { 

       array = [ response valueForKey:@"menudetails"]; 
       // Ingrediant = [ response valueForKey:@"menulist"]; 
       int currentCount = (int)array.count; 
       NSLog(@"Scroll view coun = %d", currentCount); 

       //tblView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 

       [tblView reloadData]; 

      } 
      else 
      { 


      } 
     }); 

    }else { 
     // fail.... 
     [SVProgressHUD dismiss]; 
     NSLog(@"Error: %@",error); 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      //No network connectivity - This App requires an internet connection. Please enable the same to proceed 

     }); 
    } 

}]; 

[postDataTask resume]; 

}

和表视图代码

- (UITableViewCell的*)的tableView:(UITableView的*)的tableView的cellForRowAtIndexPath:(NSIndexPath *)indexPath {

RestoCommonViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellSubCategory"]; 

    [cell.lblSubcategoryName sizeToFit]; 

[cell.IngdntDiscription sizeToFit]; 

cell.lblSubcategoryName.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"Vegitable"]]; 

cell.lblSubcategoryName.frame=CGRectMake(cell.lblSubcategoryName.frame.origin.x, cell.lblSubcategoryName.frame.origin.y, cell.lblSubcategoryName.frame.size.width,cell.lblSubcategoryName.frame.size.height); 

cell.IngdntDiscription.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"description"]]; 

cell.IngdntDiscription.frame=CGRectMake(20, 20, 20, 20); 

cell.IngdntDiscription.frame=CGRectMake(cell.IngdntDiscription.frame.origin.x, cell.lblSubcategoryName.frame.origin.y+cell.lblSubcategoryName.frame.size.height, cell.IngdntDiscription.frame.size.width,cell.IngdntDiscription.frame.size.height); 



cell.lblSubCategoryPrice.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"price"]]; 
cell.btnIngredients.tag = indexPath.row; 


return cell; 
+0

如果您在项目中使用上述代码,会得到什么结果? – user3182143

+0

这里发生了什么? – KKRocks

我不知道你的基地根据你的输出响应

我创建了示例project.I形式相同的输出,你从response.I得到相同的响应在我的dictionary.From我做以下的事情。

第一眼看到我的RestoCommonViewCell设计

enter image description here

然后

RestoCommonViewCell.h

#import <UIKit/UIKit.h> 

@interface RestoCommonViewCell : UITableViewCell 

@property (strong, nonatomic) IBOutlet UILabel *IngdntDiscription; 
@property (strong, nonatomic) IBOutlet UILabel *lblSubCategoryPrice; 
@property (strong, nonatomic) IBOutlet UILabel *lblSubcategoryName; 
@end 

RestoCommonViewCell.m

#import "RestoCommonViewCell.h" 

@implementation RestoCommonViewCell 

- (void)awakeFromNib { 
    [super awakeFromNib]; 
    // Initialization code 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
} 

@end 

ViewController.h

#import <UIKit/UIKit.h> 
#import "RestoCommonViewCell.h" 

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> 

@property (strong, nonatomic) IBOutlet UITableView *tblVwList; 

@end 

ViewController。米

#import "ViewController.h" 

@interface ViewController(){ 
    NSDictionary *dictJson; 
    NSMutableArray *arrVeg; 
} 

@end 

@implementation ViewController 

@synthesize tblVwList; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    arrVeg = [[NSMutableArray alloc]init]; 
    dictJson = [[NSDictionary alloc]init]; 
    dictJson = @{ 
        @"status": @"Success", 
        @"code": @"200", 
        @"menudetails" : 
        @{ 
          @"menu_id": @"1001", 
          @"menuname": @"Delux thali", 
          @"price" : @"$200.00", 
          @"bread" : 
          @{ 
           @"10": @"Akki rotti", 
           @"11": @"Sel roti", 
           @"max": @"1" 
          }, 
          @"rice" : 
          @{ 
           @"14": @"Jeera rice", 
           @"15": @"Biryani", 
           @"16": @"Fried rice", 
           @"max": @"1" 
          }, 
          @"Vegitable" : 
          @{ 
           @"20": @"Malai kofta", 
           @"21": @"Shahi paneer", 
           @"22": @"Palak paneer", 
           @"23": @"Paneer do piaza", 
           @"max": @"2" 
          } 

        }, 

        @"message": @"List of Tranasction", 
        @"Description": @"List of Tranasction" 
       }; 


    NSString *str20 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"20"]; 
    NSString *str21 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"21"]; 
    NSString *str22 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"22"]; 
    NSString *str23 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"23"]; 

    [arrVeg addObject:str20]; 
    [arrVeg addObject:str21]; 
    [arrVeg addObject:str22]; 
    [arrVeg addObject:str23]; 

    self.tblVwList.tableFooterView = [UIView new]; 

} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return arrVeg.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    static NSString *CellIdentifier = @"cell"; 
    RestoCommonViewCell *cell = (RestoCommonViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if(cell == nil) { 
     NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"RestoCommonViewCell" owner:nil options:nil]; 
     cell = [nibObjects objectAtIndex:0]; 

    } 

    cell.lblSubcategoryName.text = arrVeg[indexPath.row]; 

    cell.IngdntDiscription.text = [NSString stringWithFormat:@"%@",[dictJson objectForKey:@"Description"]]; 

    cell.lblSubCategoryPrice.text = [NSString stringWithFormat:@"%@",[[dictJson objectForKey:@"menudetails"] objectForKey:@"price"]]; 


    return cell; 
} 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    return 150; 
} 



@end 

见下

enter image description here

之前您在使用密钥得到的响应值输出,请邮寄或粘贴Online JSON Viewer text and view your response

您回应我检查你的回应在网上json查看器和我得到树结构化的数据。

首先我复制并粘贴回复文本

然后我查看回复。