简体   繁体   English

Swift Vapor:如何读取JSON文件?

[英]Swift Vapor: How to read a JSON file?

I'm using Vapor, the server-side Swift 4 framework for creating web servers. 我正在使用Vapor,服务器端Swift 4框架来创建Web服务器。 I have a migration that I'd like to apply that reads in from a JSON file; 我有一个我想申请的迁移,它从JSON文件中读取; however, most if not all Swift tutorials I see on this indicate using Bundle , which to my knowledge, isn't available when developing server-side swift applications, which means attempts like this don't work: 但是,大多数(如果不是全部)我在这上面看到的Swift教程都表明使用了Bundle ,据我所知,在开发服务器端swift应用程序时它不可用,这意味着这样的尝试不起作用:

if let path = Bundle.main.url(forResource: "myFile", withExtension: "json") {
...

This begs the question, given a relative file path, how can I read in a file using server-side Swift? 这引出了一个问题,给定一个相对文件路径,如何使用服务器端Swift读取文件?

Silly me. 傻我。 Vapor exposes a DirectoryConfig object from which you can retrieve the working directory of the application. Vapor公开DirectoryConfig对象,您可以从中检索应用程序的工作目录。 To parse a file, it thus becomes: 要解析文件,它将变为:

let directory = DirectoryConfig.detect()
let configDir = "Sources/App/Configuration"

do {
    let data = try Data(contentsOf: URL(fileURLWithPath: directory.workDir)
        .appendingPathComponent(configDir, isDirectory: true)
        .appendingPathComponent("myFile.json", isDirectory: false))

    // continue processing

} catch {
    print(error)
}

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

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