salongley
salongley

Reputation: 241

Vapor 3 Content to JSON to String

I am writing a Vapor 3 project that writes to a FoundationDB database in key:value pairs. I have the following code the uses a struct called Country which extends Content. I want to save the Country data as a JSON String which then will be converted to Bytes to be saved.

func createCountry(req: Request, country: Country) throws -> Future<Country>{

    return try req.content.decode(Country.self).map(to: Country.self) { country in

        let dbConnection = FDBConnector()
        let CountryKey = Tuple("iVendor", "Country", country.country_name).pack()
        let countryValue = COUNTRY_TO_JSON_TO_STRING_FUNCTION
        let success = dbConnection.writeRecord(pathKey: CountryKey, value: countryValue )

        if success {

            return country
       } //else {

            return country
        }
    }
}

How can I convert the struct to a JSON stored as a string?

Upvotes: 4

Views: 1484

Answers (1)

vzsg
vzsg

Reputation: 2896

You can use the JSONEncoder class of Foundation to encode your Country object into JSON – the output will be an UTF-8 encoded JSON string (as Data).

let encoder = JSONEncoder()

// The following line returns Data...
let data = try encoder.encode(country)

// ...which you can convert to String if it's _really_ needed:
let countryValue = String(data: data, encoding: .utf8) ?? "{}" 

Sidenote: Codable is also what powers Vapor's Content.decode method.

Upvotes: 6

Related Questions