45

我正在尝试解析 JSON 文件中的数据。我正在尝试将解析/获取的数据放入带有标签的 UIView 或 webview 中。JSON 文件如下所示:

{"bodytext": "<p>\n Some lines here about some webpage (&ldquo; <em>Site</>&rdquo;) some more lines here. \n </p>\n\n <p>\n some more stuff here </p>
}

Stack Overflow 上的帖子显示了如何解析从 Web URL 检索到的 JSON,但实际上我已经有了一个想要解析的 JSON 文件。如何从文件中解析 JSON?

4

3 回答 3

124
  1. 创建空文本文件(新文件/其他/空),例如“example.json”

  2. 将 json 字符串粘贴到文件中。

  3. 使用这些行来获取数据:

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    
于 2013-08-29T23:05:03.273 回答
18

已接受答案的 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
        }
    }
于 2015-09-26T14:06:03.640 回答
7

我遵循了这个,它工作正常

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;
 }
于 2014-09-30T06:04:11.073 回答