Vapor 3 Content to JSON to String

Vapor 3 Content to JSON to String

我正在编写一个 Vapor 3 项目,它以 key:value 对的形式写入 FoundationDB 数据库。我有以下代码,它使用一个名为 Country 的结构来扩展内容。我想将国家/地区数据保存为 JSON 字符串,然后将其转换为要保存的字节。

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

如何将结构转换为 JSON 存储为字符串?

您可以使用 Foundation 的 JSONEncoder class 将您的 Country 对象编码为 JSON – 输出将是一个 UTF-8 编码的 JSON 字符串(如数据).

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) ?? "{}" 

旁注:Codable 也是 Vapor 的 Content.decode 方法的动力。