1.代碼創(chuàng)建json文件,并保存到本地
第一步.設(shè)置****json****文件的保存路徑****
NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson.json"];
NSLog(@"%@",filePath);
****第二步**.****準(zhǔn)備存儲(chǔ)數(shù)據(jù)******
NSMutableArray *arr = [[NSMutableArray alloc]init]; //用來(lái)盛放數(shù)據(jù)的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數(shù)組的字典
****第三步.**封包數(shù)據(jù)******
NSData *json_data = [NSJSONSerialization dataWithJSONObject:json_dic options:NSJSONWritingPrettyPrinted error:nil];
****第四步.**寫(xiě)入數(shù)據(jù)******
[json_data writeToFile:filePath atomically:YES];
經(jīng)過(guò)這四步,就在本地指定路徑filePath創(chuàng)建了一個(gè)json文件。(根目錄是一個(gè)字典 key為arr value為arr數(shù)組的字典**)******
2.讀取本地json數(shù)據(jù)
NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson.json"];//獲取json文件保存的路徑
NSData *data = [NSData dataWithContentsOfFile:filePath];//獲取指定路徑的data文件
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; //獲取到j(luò)son文件的跟數(shù)據(jù)(字典)
NSArray *arr = [json objectForKey:@"arr”];//獲取指定key值的value,是一個(gè)數(shù)組
for (NSDictionary *dic in arr) {
NSLog(@"%@",[dic objectForKey:@"key1"]);//遍歷數(shù)組
}