Html 如何从 iOS 中的文件解析 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18520949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse JSON from a file in iOS?
提问by Chris
I am trying to parse data from a JSON file. I am trying to put that parsed/fetched data into a UIView with a label or in a webview. The JSON file looks something like the following:
我正在尝试解析 JSON 文件中的数据。我试图将解析/获取的数据放入带有标签的 UIView 或 web 视图中。JSON 文件类似于以下内容:
{"bodytext": "<p>\n Some lines here about some webpage (“ <em>Site</>”) some more lines here. \n </p>\n\n <p>\n some more stuff here </p>
}
There are posts here on Stack Overflow showing how to parse JSON retrieved from a Web URL, but I actually already have a JSON file I want to parse. How do I parse JSON from a file?
Stack Overflow 上有一些帖子展示了如何解析从 Web URL 检索到的 JSON,但实际上我已经有一个要解析的 JSON 文件。如何从文件中解析 JSON?
回答by ArturOlszak
Create empty text file (New File/Other/Empty) e.g. "example.json"
Paste json string into the file.
Use these lines to get the data:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"]; NSData *data = [NSData dataWithContentsOfFile:filePath]; NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
创建空文本文件(新文件/其他/空),例如“example.json”
将 json 字符串粘贴到文件中。
使用这些行获取数据:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"]; NSData *data = [NSData dataWithContentsOfFile:filePath]; NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
回答by Chris C
Swift 2.0 version of the accepted answer:
接受答案的 Swift 2.0 版本:
if let filePath = NSBundle.mainBundle().pathForResource("example", ofType: "json"), data = NSData(contentsOfFile: filePath) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
}
catch {
//Handle error
}
}
回答by wassay khan
I have followed this and it is working fine
我已经遵循了这个并且它工作正常
NSError *error = nil;
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"messages"
ofType:@"json"];
NSData *dataFromFile = [NSData dataWithContentsOfFile:filePath];
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:dataFromFile
options:kNilOptions
error:&error];
if (error != nil) {
NSLog(@"Error: was not able to load messages.");
return nil;
}