【问题标题】:How to convert Dictionary to JSON in Vapor 3?如何在 Vapor 3 中将字典转换为 JSON?
【发布时间】: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 版本更新您的代码,并告诉我们为什么它不起作用。

标签: swift vapor


【解决方案1】:

如果你有像我在这里定义的结构这样的类型,你可以简单地返回它,只要它符合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"
    }
}

【讨论】:

猜你喜欢
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 2011-12-18
  • 2018-07-04
相关资源
最近更新 更多