如何在ios中编写json文件

在这里,我正在阅读和编写一个json文件。

读取正确完成但在我写文件时它不会在json文件中写入数据。

这是我的代码。

//reading Json file.... NSString *filePath = [[NSBundle mainBundle] pathForResource:@"bookmark" ofType:@"json"]; NSData *content = [[NSData alloc] initWithContentsOfFile:filePath]; NSArray *bookmarkJson=[NSJSONSerialization JSONObjectWithData:content options:0 error:nil]; //this contains array's of dictionary.... NSDictionary *newBookmark=@{@"index":@"1.1.1.1",@"text":@"Header",@"htmlpage":@"page_name"}; //take new array to add data with previous one NSMutableArray *temp=[[NSMutableArray alloc]initWithArray:bookmarkJson]; // add object to new array... [temp insertObject:newBookmark atIndex:0]; //now serialize temp data.... NSData *serialzedData=[NSJSONSerialization dataWithJSONObject:temp options:0 error:nil]; NSString *saveBookmark = [[NSString alloc] initWithBytes:[serialzedData bytes] length:[serialzedData length] encoding:NSUTF8StringEncoding]; //now i write json file..... [saveBookmark writeToFile:@"bookmark.json" atomically:YES encoding:NSUTF8StringEncoding error:nil]; 

在“saveBookmark”(NSString)对象中我得到了正确的文件格式但在bookmark.json文件中我没有得到任何新值。

请在这件事上给予我帮助……

编辑:正如@IulianOnofrei正确指出的那样,使用文档目录来读/写文件而不是资源目录。

使用这些方法读取和写入数据,您应该解决问题:

 - (void)writeStringToFile:(NSString*)aString { // Build the path, and create if needed. NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString* fileName = @"bookmark.json"; NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName]; if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) { [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil]; } // The main act... [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO]; } - (NSString*)readStringFromFile { // Build the path... NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString* fileName = @"bookmark.json"; NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName]; // The main act... return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding]; } 

代码礼貌来自另一个SO答案: 在iPhone上编写和阅读文本文件

当然,第一次尝试从文档目录中读取此文件时,您将无法获得任何内容,因此,如果文件不存在,可能第一步是将文件复制到那里。

希望这可以帮助。