I'm developing an iPhone app and I need to show stored data in a TableView. After some research I decided that JSON would be best fit for storing the data. However, I couldn't find any tutorials explaining how to read JSON as a local file rather than from a remote source, as often is the case.
我正在开发一个iPhone应用程序,我需要在TableView中显示存储的数据。经过一些研究后,我认为JSON最适合存储数据。但是,我找不到任何教程解释如何将JSON作为本地文件而不是从远程源读取,通常就是这种情况。
Any tutorials you could recommend?
您可以推荐的任何教程?
2 个解决方案
#1
14
You can use NSJSONSerialization
for this.
您可以使用NSJSONSerialization。
NSError *deserializingError;
NSURL *localFileURL = [NSURL fileURLWithPath:pathStringToLocalFile];
NSData *contentOfLocalFile = [NSData dataWithContentsOfURL:localFileURL];
id object = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile
options:opts
error:&deserializingError];
#2
23
First of all: you need to load your local json string. Assuming the jsonstring is inside your project, to load it, first create nsstring pointing to the file:
首先:你需要加载你的本地json字符串。假设jsonstring在你的项目中,要加载它,首先创建指向该文件的nsstring:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"THENAMEOFTHEFILE" ofType:@"EXTENSIONOFYOUTFILE"];
second, load the data of file:
二,加载文件数据:
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
third, parse the data:
第三,解析数据:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil];
#1
14
You can use NSJSONSerialization
for this.
您可以使用NSJSONSerialization。
NSError *deserializingError;
NSURL *localFileURL = [NSURL fileURLWithPath:pathStringToLocalFile];
NSData *contentOfLocalFile = [NSData dataWithContentsOfURL:localFileURL];
id object = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile
options:opts
error:&deserializingError];
#2
23
First of all: you need to load your local json string. Assuming the jsonstring is inside your project, to load it, first create nsstring pointing to the file:
首先:你需要加载你的本地json字符串。假设jsonstring在你的项目中,要加载它,首先创建指向该文件的nsstring:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"THENAMEOFTHEFILE" ofType:@"EXTENSIONOFYOUTFILE"];
second, load the data of file:
二,加载文件数据:
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
third, parse the data:
第三,解析数据:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil];