用swift从文件加载json 3

我想从这个代码的文件加载一个JSONstring。

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

但是我得到了“无法加载”的消息。 代码错了吗? 或者我应该把文件放在一个特定的文件夹? 目前我把它放在一个名为模型的文件夹。

编辑:我检查了错误的内容,并没有问题的JSON文件的位置,当我尝试将其转换为string的problemoccure。 它告诉我,编码是不同的…

Error Domain = NSCocoaErrorDomain Code = 264“Die Datei”data.json“konnte nichtgeöffnetwerden,da die Textcodierung des Inhalts bestimmt wardden kann。”

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

使用这个方法来加载你的JSON,并在callback中得到结果

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