swift - 如何在 Vapor 3 中将字典转换为 JSON?

标签 swift vapor

在 Vapor 1.5 中,我曾经将 Dictionary 转换为 JSON,如下所示。
我应该如何在 Vapor 3.1 中执行此操作? 在文档中它说我需要创建结构类型并使其符合可编码协议(protocol)。
是否有另一种方法可以在不创建新结构的情况下转换现有字典?

   func makeCustomJSON(clientData: DataFromClientChargeWithCard, paymentID:String,customer: String) throws -> JSON {



    var dictionaryOfStrings = [String:String]()


    dictionaryOfStrings["BookingState"] = "Active"
    dictionaryOfStrings["BookingStateTimeStamp"] = clientData.TimeStampBookingSavedInDB

    dictionaryOfStrings["ChangesMadeBy"] = "User"
    dictionaryOfStrings["PaymentID"] = paymentID
    dictionaryOfStrings["DateAndTime"] = clientData.DateAndTime
    dictionaryOfStrings["RatePriceClient"] = clientData.RatePriceClient
    dictionaryOfStrings["Locality"] = clientData.Locality
    dictionaryOfStrings["StripeCustomerID"] = customer

    //some more properties below...

    let response:JSON
    do {
        response = try JSON(node: dictionaryOfStrings)
    }catch let error as NSError {
        let message = "dictionaryOfStrings can't be converted in JSON"
        drop.log.error(message)
        logErr.prints(message: message, code: error.code)
        throw NSError(domain: "errorDictionary", code: 400, userInfo: ["error" : error.localizedDescription])
    }
    return response
 }

最佳答案

如果您有一个类似于我在此处定义的结构的类型,只要它符合Content,您就可以简单地返回它。

import Vapor
import FluentSQLite

struct Employee: Codable {
    var id: Int?
    var name: String

    init(name:String) {
        self.name = name
    }
}

extension Employee: SQLiteModel {}

extension Employee: Migration {}

extension Employee: Parameter {}

extension Employee: Content { }

然后你可以简单地定义一个路由并返回它。

router.get("test") { req in
    return Employee(name: "Alan")
}

如果你想使用字典,你可以使用 JSONSerialization 并返回一个字符串。

router.get("test2") { req -> String in

    let employeeDic: [String : Any] = ["name":"Alan", "age":27]

    do {
        let data = try JSONSerialization.data(withJSONObject: employeeDic, options: .prettyPrinted)
        let jsonString = String(data: data, encoding: .utf8)
        return jsonString ?? "FAILED"

    }catch{
        return "ERROR"
    }
}

关于swift - 如何在 Vapor 3 中将字典转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51214180/

相关文章:

ios - 如何用图像创建侧滚动条效果?

ios - 在 Realm 中查询

swift - 如何为多个实体使用 AuthMiddleware?

swift - 使用字符串按键访问类扩展中结构中的静态变量

swift - Swift 中可变位的移位行为

swift - 在函数中传递未知数量的参数

validation - 未声明的类型 'valid',没有这样的模块 'Validation'

swift - Vapor 3 Beta 端点请求示例

swift - Vapor Xcode 项目中的多个目标

macos - 将 Nginx 配置为 Vapor API 的代理