gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:57:19 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com