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"]);
//遍歷數組
}