简体   繁体   English

如何快速读取Documents目录中的json文件?

[英]How can I read a json file in the Documents Directory in swift?

I have some JSON files in a sever. 我在服务器中有一些JSON文件。 I download them and save them in the documents directory. 我下载它们并将其保存在documents目录中。 But I can't read them. 但是我看不懂它们。 Here is my code: 这是我的代码:

let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    let textFileURL = documentsPath.appendingPathComponent("resource/data/introduction")
    let fileURLString = textFileURL?.path
    if FileManager.default.fileExists(atPath: (fileURLString)!){
        print("success")
    }
    if let path = Bundle.main.path(forResource: "test" , ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            let jsonObj = JSONSerializer.toJson(data)
            print(jsonObj)
        } catch let error {
            print(error.localizedDescription)
        }
    } else {
        print("Invalid filename/path.")
    }

If you change this line: 如果更改此行:

let jsonObj = JSONSerializer.toJson(data)

to this: 对此:

let jsonObj = try JSONSerialization.jsonObject(with:data, options:JSONSerialization.ReadingOptions(rawValue:0))

The code should work. 该代码应该工作。 I don't know where the first line I highlighted came from - perhaps you are using a third-party library? 我不知道我突出显示的第一行来自哪里-也许您正在使用第三方库? If so, you might want to mention what you are using so that we can see all the elements that go into the code. 如果是这样,您可能要提及您在使用什么,以便我们可以看到代码中包含的所有元素。

If you are using the standard JSON serialization library and the code was a simple typing error or something, could you also mention what the error you see is or what happens when the code doesn't work? 如果您使用的是标准JSON序列化库,并且代码是一个简单的键入错误或某些错误,您还可以提及所看到的错误是什么,或者当代码不起作用时会发生什么?

There are two possible cases: 有两种可能的情况:

A. In case you have multiple json file with the same name in your project but they are in different directories ( "Environment/production/myjsonfile.json" and "Environment/development/myjsonfile.json" ): "Environment/production/myjsonfile.json" :如果您的项目中有多个具有相同名称的json文件,但是它们位于不同的目录中"Environment/production/myjsonfile.json""Environment/development/myjsonfile.json" ):

  • you have to specify the directory Bundle.main.path(forResource: "myjsonfile", ofType: "json", inDirectory: "Environment/production") 您必须指定目录Bundle.main.path(forResource: "myjsonfile", ofType: "json", inDirectory: "Environment/production")
  • the directory "Environment" should be added as a Folder in your main bundle (App Target) and should be displayed in blue color (yellow it is when it is being added as a Group). 目录"Environment"应作为Folder添加到您的主捆绑包(应用程序目标)中,并应显示为blue color (将其作为组添加时为黄色)。 Just delete its reference and add it again (remember to select to add it as a Folder and not as a Group) 只需删除其引用并再次添加即可(请记住选择将其添加为文件夹而不是组)

B. In case you have only one kind of myjsonfile.json in your project , than just use Bundle.main.path(forResource: "myjsonfile", ofType: "json") and it will find it in your main Bundle (App Target). B.如果您的项目中只有一种myjsonfile.json ,而不仅仅是使用Bundle.main.path(forResource: "myjsonfile", ofType: "json") ,它将在您的主Bundle中找到它(应用程序目标)。

I had the same problem, but researching and compiling information about problem solving, here I leave you my job, I hope to help. 我遇到了同样的问题,但是研究和收集了有关解决问题的信息,在这里,我要离开我的工作,希望对您有所帮助。

import UIKit

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()

 //llamar metodo para descargar json
        descargar()

}

//------------------Descargar json--------------------------------------------------------  
func descargar() {

    //Create URL to the source file you want to download
    let fileURL = URL(string: "http://10.32.14.124:7098/Servicio.svc/getCentralesMovilJSON/")

    // Create destination URL
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!

    //agregar al destino el archivo
    let destinationFileUrl = documentsUrl.appendingPathComponent("centrales.json")

    //archivo existente???....................................................
    let fileExists = FileManager().fileExists(atPath: destinationFileUrl.path)

    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)

    let request = URLRequest(url:fileURL!)

    // si el archivo centrales.json ya existe, no descargarlo de nuevo y enviar ruta de destino.........................................................................
    if fileExists == true {
        print("archivo existente")
        print(destinationFileUrl  )
        //llamar metodo para parsear el json............................................
        parseo()

    }

// si el archivo centrales.json aun no existe, descargarlo y mostrar ruta de destino..........................................................................
    else{
        print("descargar archivo")

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success se ah descargado correctamente...................................
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
                print(destinationFileUrl)
                //llamar metodo para parsear el json............................................
                self.parseo()
            }

            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }

        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
        }
        }
    task.resume()

    }}




//-----------------------------Extraer datos del archivo json----------------------------

func parseo(){

    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let destinationFileUrl = documentsUrl.appendingPathComponent("centrales.json")




    do {

        let data = try Data(contentsOf: destinationFileUrl, options: [])
        let centralArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] ?? []

        print(centralArray)


    }catch {
        print(error)
    }

}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM