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

时间:2017-06-06 16:46:29

标签: ios objective-c json

我有这样的json {
   “状态”:“成功”,    “代码”: “200”,    “menudetails”:{
      “menu_id”: “1001”,       “menuname”:“Delux thali”,       “价格”: “$ 200.00”,       “面包”:{
         “最大”: “1”,          “10”:“Akki rotti”,          “11”:“Sel roti”       },       “米”:{
         “最大”: “1”,          “14”:“Jeera rice”,          “15”:“布瑞雅尼”          “16”:“炒饭”       },       “Vegitable”:{
         “最大”: “2”,          “20”:“Malai kofta”,          “21”:“Shahi paneer”,          “22”:“Palak paneer”,          “23”:“Paneer do piaza”       }    },    “消息”:“Tranasction列表”,    “描述”:“Tranasction列表” } 我试着调用这个API

- (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;

1 个答案:

答案 0 :(得分:0)

我不知道您的基本网址,参数。根据您的输出回复

我创建了示例项目。我形成了与从响应中得到的相同的输出。我在我的字典中得到相同的响应。从那里我做了以下事情。

首先看看我的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.m

#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 viewer中查看你的回复,我得到树形结构数据。

首先,我将您的回复复制并粘贴到文本中

然后我查看回复。