【问题标题】:How do I parse JSON from a file in iOS? [closed]如何从 iOS 中的文件中解析 JSON? [关闭]
【发布时间】:2013-09-02 11:27:28
【问题描述】:

我正在尝试解析 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?

【问题讨论】:

  • 刚刚把json文件做成了html文件,读取并显示在web视图上。如果有人有更好的方法,请发表评论并告诉我。

标签: html ios json parsing


【解决方案1】:
  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];
    

【讨论】:

  • 上个月我复制粘贴了这个sn-p超过100次
  • @lucaslt89 是时候让它成为 Xcode sn-p:nshipster.com/xcode-snippets
  • 或者一些帮助类/类别
【解决方案2】:

已接受答案的 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
        }
    }

【讨论】:

    【解决方案3】:

    我已经按照这个,它工作正常

    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;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 2022-01-06
      • 2013-10-21
      • 2018-04-07
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多