我正在编写一个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?
答案 0 :(得分:4)
您可以使用Foundation的JSONEncoder类将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
方法的动力。