IOS中本地存储和查看 - json数据

1.代码创建json文件,并保存到本地

第一步.设置****json****文件的保存路径****

NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson.json"];

NSLog(@"%@",filePath);

****第二步**.****准备存储数据******

NSMutableArray *arr = [[NSMutableArray alloc]init]; //用来盛放数据的value

NSDictionary *dic = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3",@"key4":@"value4"};

NSDictionary *dic1 = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3",@"key4":@"value4"};

NSDictionary *dic2 = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3",@"key4":@"value4"};

[arr addObjectsFromArray:@[dic,dic1,dic2]];

NSDictionary *json_dic = @{@"arr":arr};//key为arr value为arr数组的字典

****第三步.**封包数据******

NSData *json_data = [NSJSONSerialization dataWithJSONObject:json_dic options:NSJSONWritingPrettyPrinted error:nil];

****第四步.**写入数据******

[json_data writeToFile:filePath atomically:YES];

经过这四步,就在本地指定路径filePath创建了一个json文件。(根目录是一个字典 key为arr value为arr数组的字典**)******

2.读取本地json数据

NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson.json"];//获取json文件保存的路径

NSData *data = [NSData dataWithContentsOfFile:filePath];//获取指定路径的data文件

id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; //获取到json文件的跟数据(字典)

NSArray *arr = [json objectForKey:@"arr”];//获取指定key值的value,是一个数组

for (NSDictionary *dic in arr) {

    NSLog(@"%@",[dic objectForKey:@"key1"]);//遍历数组

}

你可能感兴趣的:(IOS中本地存储和查看 - json数据)