bibscy
bibscy

Reputation: 2718

How to convert Dictionary to JSON in Vapor 3?

In Vapor 1.5 I used to convert Dictionary to JSON as shown below.
How should I do it in Vapor 3.1? In docs it says I need to create struct type and conform it to codable protocol.
Is there another method that would enable to convert the existing dictionary without creating new struct?

   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
 }

Upvotes: 2

Views: 800

Answers (1)

user7649191
user7649191

Reputation:

If you have a type like the struct that I have defined here you can simply return it, as long as it conforms to 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 { }

and then you can simply define a route and return it.

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

if you want to use dictionary you can use the JSONSerialization and return a string.

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"
    }
}

Upvotes: 1

Related Questions