欢迎访问宙启技术站
智能推送

用json方法解析本地数据,并显示在tableView上面

发布时间:2023-05-16 18:42:29

一、什么是JSON

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。JSON的数据格式是JavaScript语言中的对象和数组的表示形式。它可以用来描述复杂的数据结构。

二、如何解析JSON数据

iOS开发中我们通常使用Foundation框架中的NSJSONSerialization类来解析JSON格式的数据。NSJSONSerialization提供了将JSON数据转换为Foundation对象和将Foundation对象转换为JSON数据的方法。在项目中,我们一般使用第三方库AFNetworking来进行网络请求获取JSON格式的数据,也可以手动创建JSON格式的本地数据。

三、使用NSJSONSerialization解析本地数据

我们先创建一个JSON数据文件,例如:

{

    "students": [

        {

            "id": "001",

            "name": "Tom",

            "age": "18",

            "gender": "male"

        },

        {

            "id": "002",

            "name": "Lucy",

            "age": "20",

            "gender": "female"

        },

        {

            "id": "003",

            "name": "Jack",

            "age": "22",

            "gender": "male"

        },

        {

            "id": "004",

            "name": "Lily",

            "age": "19",

            "gender": "female"

        }

    ]

}

然后在项目中添加该文件,并创建一个名为Student的类,其中包含id、name、age、gender四个属性。

@interface Student : NSObject

@property (nonatomic, copy) NSString *id;

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *age;

@property (nonatomic, copy) NSString *gender;

@end

@implementation Student

@end

我们的目标是将该JSON数据解析出来,并将其中的学生信息显示在UITableView中,因此,我们需要创建一个包含UITableView的ViewController,并在其中实现tableView的数据源方法。

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

    return self.dataArray.count;

}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    Student *stu = self.dataArray[indexPath.row];

    cell.textLabel.text = stu.name;

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@  %@", stu.age, stu.gender];

    return cell;

}

然后我们就可以在viewDidLoad方法中进行JSON数据的解析了。

- (void)viewDidLoad {

    [super viewDidLoad];

    self.title = @"Student List";

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

    self.dataArray = [NSMutableArray array];

    NSError *error = nil;

    NSString *path = [[NSBundle mainBundle] pathForResource:@"StudentData" ofType:@"json"];

    NSData *jsonData = [[NSData alloc] initWithContentsOfFile:path];

    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

    if (error) {

        NSLog(@"JSON解析出错:%@", error);

    } else {

        NSArray *students = [jsonDict objectForKey:@"students"];

        for (NSDictionary *dict in students) {

            Student *stu = [[Student alloc] init];

            stu.id = [dict objectForKey:@"id"];

            stu.name = [dict objectForKey:@"name"];

            stu.age = [dict objectForKey:@"age"];

            stu.gender = [dict objectForKey:@"gender"];

            [self.dataArray addObject:stu];

        }

        [self.tableView reloadData];

    }

}

在该代码中,我们首先获取StudentData.json文件的路径,并将其读成NSData类型的数据。然后通过NSJSONSerialization类的JSONObjectWithData:options:error:方法将其解析成Foundation对象,类型为NSDictionary。我们从NSDictionary中取出键为“students”的数组,遍历其中每个NSDictionary,并将其转化为Student对象后加入到dataArray数组中。最后调用tableView的reloadData方法将数据显示在界面上。

四、总结

学习JSON解析是iOS开发的基础,适用于从网络中获取数据、同时可以用于解析本地数据等场景,掌握其使用方法对于我们的项目开发有很大的帮助。在实际开发中,我们还可以使用其他的第三方库来解析JSON数据,例如YYModel、MJExtension等,以提高效率和减少代码量。