解析数据的步骤

解析数据的步骤

1、plist文件数据

    //获取文件路径

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"plist"];

    

    //从文件路径中提取数组

    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];

    

    //初始化数据数组

    _dataArray = [[NSMutableArray alloc] initWithCapacity:0];

    

    //遍历数组,进行添加模型

    for (NSDictionary *dic in array) {

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

        [student setValuesForKeysWithDictionary:dic];

        [_dataArray addObject:student];

        [student release];

    }

2、解析JSON数据

    //获取json数据的路径

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"json"];

    

    //获取NSData对象

    NSData *data = [NSData dataWithContentsOfFile:filePath];

    

    //解析JSON数据

    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    

    //初始化模型数组

    _dataArray = [[NSMutableArray alloc] initWithCapacity:0];

    

    for (NSDictionary *dic in array) {

        Model *model = [[Model alloc] init];

        [model setValuesForKeysWithDictionary:dic];

        [_dataArray addObject:model];

        [model release];

    }

从上面两个例子可以看出来,解析数据的步骤大概可以分为以下几步:

1、获取数据的路径

2、从文件路径中提取对应的数据类型

3、解析数据

(1)初始化模型数组

(2)解析的最终结果都是将字典转换成模型,所以我们要理清层次关系,明白字典是有键—值对组成的。

(3)将模型加到事先声明的字典或者数组中。

原文地址:https://www.cnblogs.com/d-mm/p/5210222.html