iOS--JSON解析后如何获取数据,并且展示到相应cell上
首先建立一个singleview工程,并在故事版中添加UITableView,连好数据源和代理。
在.h文件中添加数据源和代理方法,并且声明一个UITableView的变量,代码如下。
?
1
2
3
4
5
6
7
#import@interface ViewController : UIViewController@property (weak, nonatomic) IBOutlet UITableView *tableview;@end剩下的代码比较简单,我就直接贴代码了,已经在里面详细注释了。
.m文件如下
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#import "ViewController.h"@interface ViewController (){NSMutableArray *_listarr;//定义一个存放数据的容器。}@end@implementation ViewController- (void)viewDidLoad{[super viewDidLoad];//ios7新特性,这个请自行百度。[self.tableview registerClass:[UITableViewCellclass] forCellReuseIdentifier:@"Cell"];NSError *error;//加载一个NSURL对象NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.touzhu.cn/ex_jc.aspx?state=0&ifgetclass=1"]];//将请求的url数据放到NSData对象中NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];//IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];//获取数组list的内容NSArray *list = [dic objectForKey:@"list"];NSLog(@"list数组的内容为--》%@", list );//初始化成员变量_listarr = [[NSMutableArray alloc]init];//遍历数组list里的内容for(inti = 0; i<[list count]; i++) {//按数组中的索引取出对应的字典NSDictionary *listdic = [list objectAtIndex:i];//通过字典中的key取出对应value,并且强制转化为NSString类型NSString *teamname = (NSString *)[listdic objectForKey:@"name_j"];//将获取的value值放到数组容器中[_listarr addObject:teamname];NSLog(@"name内容为--》%@", teamname );}}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{//必须返回与数据容器一样的数量,否则会报数据越界错return[_listarr count];}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{staticNSString *CellIdentifier = @"Cell";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];//将要显示的数据赋值到cell上cell.textLabel.text = [_listarr objectAtIndex:indexPath.row];returncell;}@end
本文转自 卓行天下 51CTO博客,原文链接:http://blog.51cto.com/9951038/1747480,如需转载请自行联系原作者