我将如何将 JSON 文件从 web 服务保存到本地 JSON 文件?

Posted

技术标签:

【中文标题】我将如何将 JSON 文件从 web 服务保存到本地 JSON 文件?【英文标题】:How would I go about saving a JSON file from a webservice to a local JSON file? 【发布时间】:2013-09-05 09:23:11 【问题描述】:

我目前正在使用来自远程 Web 服务的 JSON 数据(NSArray 格式)填充 UITableView。我想通过调用 web 服务并将 JSON 数据存储到本地文件来加速应用程序。

另外,这是一个好方法吗?这样用户就不必一直下载数据了?

我坚持的是如何将远程 JSON 文件保存到本地文件。在我的-(void)saveJsonWithData:(NSData *)data 方法中如何保存远程数据。

这是我目前使用的代码(来自一些 *** 搜索)

-(void)saveJsonWithData:(NSData *)data

 NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/data.json"];

 [data writeToFile:jsonPath atomically:YES];

-(NSData *)getSavedJsonData
    NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/data.json"];

    return [NSData dataWithContentsOfFile:jsonPath]

然后调用函数为

- (void)connectionDidFinishLoading:(NSURLConnection *)connection


    [self saveJsonWithData:data];

感谢帮助

【问题讨论】:

【参考方案1】:

ios 上,您应该使用 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) 来获取文档目录。没有用户目录。

【讨论】:

谢谢!但是你知道我如何将 NSURL 中的 json 保存到本地 json 文件中吗? 您的方法将保存数据。我假设您已经有一些其他代码可以进行下载。【参考方案2】:

让iOS做JSON解析,然后通过输出流写入纯文本文件

NSData *jsonData = yourData;
NSError *error;

// array of dictionary
NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];

if (error) 
    NSLog(@"Error: %@", error.localizedDescription);
 else 
    NSArray *documentsSearchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [documentsSearchPaths count] == 0 ? nil : [documentsSearchPaths objectAtIndex:0];

    NSString *fileName = @"file.json";

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

    NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];
    [outputStream open];

    [NSJSONSerialization writeJSONObject:array
                                toStream:outputStream
                                 options:kNilOptions
                                   error:&error];
    [outputStream close];

【讨论】:

以上是关于我将如何将 JSON 文件从 web 服务保存到本地 JSON 文件?的主要内容,如果未能解决你的问题,请参考以下文章