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"]);//遍历数组

}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容