ios - 使用 swift 3 从文件加载 json

标签 ios json swift

我正在尝试使用此代码从文件加载 json 字符串。

if let filepath = Bundle.main.path(forResource: "data", ofType: "json") {
    do {
        let contents = try String(contentsOfFile: filepath)
        print(contents)
    } catch {
        // contents could not be loaded
        print("could not be loaded")
    }

} else {

}

但我收到“无法加载”消息。代码有错吗?还是我应该将文件放在特定文件夹中?目前我将它放在一个名为 models 的文件夹中。

编辑: 我检查了错误内容,json 文件的位置没有问题,当我尝试将其转换为字符串时出现问题。它告诉我编码不同......

Error Domain=NSCocoaErrorDomain Code=264 "Die Datei „data.json“ konnte nicht geöffnet werden, da die Textcodierung des Inhalts nicht bestimmt werden kann."

最佳答案

首先确保你已经标记了copy item if needed复选标记,并且你的目标在你添加你的.json文件时也被标记了,之后你的主要问题是你加载文件的方式,您需要使用 Data 而不是 String

来执行此操作

使用此方法加载您的 json 并在回调中获取结果

     func loadJSON(finishedClosure:@escaping ((_ jsonObject:[String:AnyObject]?,_ error: NSError?) ->Void))
{
    DispatchQueue.global().async {
        guard let path = Bundle.main.path(forResource: "yourJSON", ofType: "json") else{
            DispatchQueue.main.async {
                finishedClosure(nil, NSError(domain: "JSON file don't founded", code: 998, userInfo: nil)) 
            }
            return
        }
        //Load file data part
        guard let jsonData = (try? Data(contentsOf: URL(fileURLWithPath: path))) else{
            DispatchQueue.main.async {
                finishedClosure(nil, NSError(domain: "can convert to data", code: 999, userInfo: nil))  
            }
            return
        }

        do {
            if let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:AnyObject]
            {
                DispatchQueue.main.async {
                    finishedClosure(jsonObject,nil)
                }
            }
        } catch let error as NSError {
            print(error)
            DispatchQueue.main.async {
                finishedClosure(nil,error)
            }
        }
    }
}

关于ios - 使用 swift 3 从文件加载 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45882205/

相关文章:

ios - 表格 View - 删除项目时清空背景空间

ios - Xcode 7.2 - 在泄漏检测期间,应用程序未连接到互联网

ios - 重新生成配置文件

JavaScript - 将两个 JSON 请求组合成一个对象

ios - UICollectionView 在某些单元格上重复标签和图像

swift - viewDidApper 时调用可重复任务

ios - 当 UITabBar 不是 rootViewController 时,如何以编程方式将 UITabBar 与带有 NIB 的不同 ViewController 链接

iphone - 使用 FMDB 执行 sqlite 查询时遇到问题

javascript - 访问 D3 中的 JSON 值

php - 为什么将空白字符串的 json_encode 添加到数组中?