我正在编写一个 Vapor 3 项目,该项目以键:值对的形式写入 FoundationDB 数据库。我有以下代码,使用一个名为 Country 的结构来扩展 Content。我想将国家/地区数据保存为 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何将结构转换为以字符串形式存储的 JSON?
您可以使用Foundation 的JSONEncoder类将您的 Country 对象编码为 JSON \xe2\x80\x93 ,输出将是 UTF-8 编码的 JSON 字符串(作为数据)。
\n\nlet encoder = JSONEncoder()\n\n// The following line returns Data...\nlet data = try encoder.encode(country)\n\n// ...which you can convert to String if it\'s _really_ needed:\nlet countryValue = String(data: data, encoding: .utf8) ?? "{}" \nRun Code Online (Sandbox Code Playgroud)\n\n旁注:可编码也是 VaporContent.decode方法的动力。
| 归档时间: |
|
| 查看次数: |
1369 次 |
| 最近记录: |