天天看点

OC基础学习——如何解析plist文件和数据的归档和解档与json数据的解析

一、plist文件的解析

 NSString *path = @"/Users/qf/Desktop/oc课堂练习/Plist文件的新建与解析/Plist文件的新建与解析/Property\ List.plist";

        //1.解析plist文件中的内容1.首先看其结构,如果外部结构为字典就用字典来接受它,如果外部是数组就用数组来接受

        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:path];

        //快速遍历字典中数组(注意快速遍历只能遍历key)

        for (NSString *key in dic) {

            NSLog(@"%@",[dic objectForKey:key]);

        }

        //.网plist文件中添加内容,注意添加的结构要与其结构相同

        NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];

        //.将数组加入当原来的字典中

        [dic setObject:array forKey:@"pengyue"];

        // .将字典写入文件中

        [dic writeToFile:path atomically:YES];

二、数据的归档和解档

        //1.数组的归档(其实质就是转为NSData内容)

        NSArray *array = [NSArray arrayWithObjects:@"2",@"3",@"4", nil];

     NSData *data =   [NSKeyedArchiver archivedDataWithRootObject:array];

        //.解档

        NSArray *new = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        NSLog(@"%@",new);

        //2.________对自定义的对象进行归档——————

        Person *p1 = [[Person alloc] init];

        p1.name = @"yang";

        p1.age = [NSNumber numberWithInt:23];

        Person *p2 = [[Person alloc] init];

        p2.name = @"peng";

        p2.age = [NSNumber numberWithInt:20];

        NSArray *dd = [NSArray arrayWithObjects:p1, p2,nil];

        NSData *dota = [NSKeyedArchiver archivedDataWithRootObject:dd];

        NSArray *yy = [NSKeyedUnarchiver unarchiveObjectWithData:dota];

        NSLog(@"%@",yy);

三、对本地json数据的解析

//1.首先要分析json数据的数据结构,

        //1.1首先获取路径

        NSString *path = @"/Users/qf/Downloads/day10-2/topic.txt";

        //.读取文件内容

        NSData *data = [NSData dataWithContentsOfFile:path];

        //对其解析

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

        //.遍历数组

        // 创建一个数组来保存数据对象

        NSMutableArray *new = [[NSMutableArray alloc] init];

        for (NSMutableDictionary*dic in array) {

            //.创建一个对象用来保存字典中的数据

            Contents *content = [[Contents alloc] init];

            content.name = [dic objectForKey:@"Name"];

            content.pic = [dic objectForKey:@"Pic"];

            content.ProjectID = [dic objectForKey:@"ProjectID"];

            content.ProjType = [dic objectForKey:@"ProjType"];

            content.Url = [dic objectForKey:@"Url"];

            [new addObject:content];

        }

        //.遍历对象数组,将其打印

        for (Contents *c in new) {

            NSLog(@"%@",c);

        }