如何在ios中编写json文件 [英] how to write json file in ios

查看:759
本文介绍了如何在ios中编写json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



读取操作正确,但在编写文件时,它不会在json文件中写入数据。 / p>

这是我的代码。

  //读取Json文件.. .. 
NSString * filePath = [[NSBundle mainBundle] pathForResource:@bookmarkofType:@json];

NSData * content = [[NSData alloc] initWithContentsOfFile:filePath];
NSArray * bookmarkJson = [NSJSONSerialization JSONObjectWithData:内容选项:0错误:nil];
//这包含字典的数组....
NSDictionary * newBookmark = @ {@index:@1.1.1.1,@text:@Header,@htmlpage :@ PAGE_NAME};

//使用新数组添加前一个数据
NSMutableArray * temp = [[NSMutableArray alloc] initWithArray:bookmarkJson];
//将对象添加到新数组...
[temp insertObject:newBookmark atIndex:0];

//现在序列化临时数据....
NSData * serialzedData = [NSJSONSerialization dataWithJSONObject:temp options:0 error:nil];

NSString * saveBookmark = [[NSString alloc] initWithBytes:[serialzedData bytes] length:[serialzedData length] encoding:NSUTF8StringEncoding];

//现在我写json文件.....
[saveBookmark writeToFile:@bookmark.jsonatomically:YES encoding:NSUTF8StringEncoding error:nil];

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



请帮助我......

解决方案

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



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

   - (void)writeStringToFile:(NSString *)aString { 

//构建路径,并根据需要创建。
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];
}

//主要行为......
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}

- (NSString *)readStringFromFile {

//构建路径...
NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask) ,YES)objectAtIndex:0];
NSString * fileName = @bookmark.json;
NSString * fileAtPath = [filePath stringByAppendingPathComponent:fileName];

//主要行为...
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}

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



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



希望这有帮助。


Here i am reading and writing a json file.

Reading is done correctly but while i am writing a file it doesn't write data in json file.

Here is my code.

//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];

In "saveBookmark" (NSString)object i got correct file format but in bookmark.json file i didn't got any new values.

Please help me with this......

解决方案

EDIT: As correctly pointed out by @IulianOnofrei, use the document directory to read/write files and not the resources directory.

Use these methods to read and write data, and you problem should be solved:

- (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];
}

Code courtesy from another SO answer found here: Writing and reading text files on the iPhone

And of course, the first time you try to read this file from the documents directory you won't get anything, so maybe the first step would be to copy the file there if it does not exist.

Hope this helps.

这篇关于如何在ios中编写json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆