如何解析iOS中的文件中的JSON?

Chr*_*ris 43 html parsing json ios

我试图解析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>
}
Run Code Online (Sandbox Code Playgroud)

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

Art*_*zak 122

  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];
    
    Run Code Online (Sandbox Code Playgroud)

  • 我在上个月复制粘贴这个片段超过100次 (17认同)
  • @ lucaslt89时间让它成为一个Xcode片段:http://nshipster.com/xcode-snippets/ (2认同)

Chr*_*s C 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
        }
    }
Run Code Online (Sandbox Code Playgroud)


was*_*han 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;
 }
Run Code Online (Sandbox Code Playgroud)