簡體   English   中英

如何在文件管理器中快速讀取json文件?

[英]how to read json file in filemanager swift?

我試圖讀取 zip 文件中的 json 文件,在我使用 alamofire 下載文件后,我使用 SSZipArchive 提取了該文件。 我從 zip 中獲得了 2 個 json 文件,但是我無法讀取 json 的內容。 我如何才能讀取該文件?

這是我的代碼:

 @IBAction func downloads(_ sender: UIButton){

    let urlString : String = ""
    let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)



    Alamofire.download(urlString, method: .get, encoding: URLEncoding.default, to: destination)
        .downloadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
            print("Progress: \(progress.fractionCompleted)")
            print(progress)
        }
        .validate { request, response, temporaryURL, destinationURL in
            return .success
        }
        .responseJSON { response in


            print(response)
            debugPrint(response)
            print(response.destinationURL?.path)
            print(response.destinationURL?.absoluteString)
            let fileName = response.destinationURL!.path

            guard let unzipDirectory = self.unzipPath(fileName: fileName) else {return}

            let success = SSZipArchive.unzipFile(atPath: (response.destinationURL?.path)!, toDestination: unzipDirectory)
            print(success)

            print(unzipDirectory)
            if !success {
                return
            }



            var items: [String]
            do {
                items = try FileManager.default.contentsOfDirectory(atPath: unzipDirectory)

                for item in items{
                    print("jsonFile: \(item)")
                }



            } catch {
                return
                }
    }
}

  func unzipPath(fileName:String) -> String? {
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let pathWithComponent = path.appendingPathComponent("\(fileName)")
    do {
        try FileManager.default.createDirectory(atPath: pathWithComponent, withIntermediateDirectories: true, attributes: nil)
    } catch {
        return nil
    }
    return pathWithComponent
}

這個截圖響應:

在此處輸入圖片說明

不確定,但對於 JSON Readable,您可以調用此方法

func readJson() {
    let url = Bundle.main.url(forResource: "input_ios", withExtension: "json")
    let data = NSData(contentsOf: url!)
    do {
        let object = try JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments)
        if let dictionary = object as? [String: AnyObject] {
            if let Timeline = dictionary["timeline"] as? [[String:Any]] {
                timelArr = Timeline
                feedTbl.reloadData()
            }
        }
    } catch {
    }
}

並更改文件名(您的文件名),然后獲取數據。 我在這里顯示在 tableview 中。

 if let Timeline = dictionary["timeline"] as? [[String:Any]] 

文件中有時間軸鍵,因此更改文件中的任何內容。

嘗試以下

  • 獲取該 json 的路徑

    let path = Bundle.main.path(forResource: "test", ofType: "json")
  • 轉換成數據

    let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
  • 解碼成反射模型

     //make a model to reflect your json and place it instead of "CustomModel".self let model = JSONDecoder().decode(CustomModel.self, from: data)

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM