gpt4 book ai didi

json - Vapor 3 内容到 JSON 到字符串

转载 作者:搜寻专家 更新时间:2023-10-31 22:17:51 25 4
gpt4 key购买 nike

我正在编写一个 Vapor 3 项目,它以键值对的形式写入 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?

最佳答案

您可以使用 JSONEncoder Foundation 类将您的 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 方法的动力。

关于json - Vapor 3 内容到 JSON 到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51609382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com