Vapor 3内容到JSON到字符串

Vapor 3内容到JSON到字符串,json,swift,vapor,Json,Swift,Vapor,我正在写一个Vapor 3项目,它以键:值对的形式写入FoundationDB数据库。我有以下代码,它使用一个名为Country的结构来扩展内容。我想将国家数据保存为JSON字符串,然后将其转换为要保存的字节 func createCountry(req: Request, country: Country) throws -> Future<Country>{ return try req.content.decode(Country.self).map(to: C

我正在写一个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
        }
    }
}
func createCountry(请求,国家/地区)抛出->未来{
返回try-req.content.decode(Country.self).map(to:Country.self){Country in
设dbConnection=FDBConnector()
让CountryKey=Tuple(“iVendor”,“Country”,Country.Country\u name).pack()
让countryValue=COUNTRY\u TO\u JSON\u TO\u STRING\u函数
让success=dbConnection.writeRecord(路径键:CountryKey,值:countryValue)
如果成功{
返回国
}//否则{
返回国
}
}
}
如何将结构转换为字符串存储的JSON?< /p> < p>您可以使用基础类将您的国家对象编码为JSON——输出将是UTF-8编码的JSON字符串(如数据)。

旁注:Codable也是Vapor的
内容的动力。解码方法。

谢谢。这是我苦苦挣扎的最后一句话。FoundationDB是一个NoSQL数据库,我决定将一些数据存储为整个JSON对象。我的想法是希望能够直接从数据库中读取它们,并将它们直接传递到web前端。FoundationDB只存储编码为字节的数据,因此我需要能够将其转换为字符串,因为我无法直接存储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) ?? "{}"