【发布时间】:2018-07-06 16:10:11
【问题描述】:
在 Vapor 1.5 中,我曾经将 Dictionary 转换为 JSON,如下所示。
我应该如何在 Vapor 3.1 中做到这一点?
在文档中它说我需要创建结构类型并将其符合可编码协议。
是否有另一种方法可以在不创建新结构的情况下转换现有字典?
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
}
【问题讨论】:
-
在 Vapor3 中添加了可编码支持,请查看文档以获取介绍:docs.vapor.codes/3.0/getting-started/content
-
@nathan 我知道我可以构建一个结构,使其符合 Context 协议,然后返回该结构的一个实例。但是,我想知道是否有任何替代方法可以做到这一点,例如使用我们以前使用的方法
try JSON(node: dictionaryOfStrings) -
不再存在单独的 JSON 类型的概念。任何符合 Content 的结构/类都可以返回。如果可以,请使用 Content 使用 Vapor3 版本更新您的代码,并告诉我们为什么它不起作用。