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数组的字典)
网友评论