我不得不在一个项目中使用FoundationDB数据库。它将数据存储为键:作为Bytes存储的值对。我想存储一个映射到我所拥有的结构的JSON对象。我希望能够将数据保存为编码的JSON对象,然后通过从DB读取值Bytes来重新创建JSON对象。
在我的CreateRecord函数中,我在请求中传递一个JSON,并使用它创建我的国家对象。我需要将类型数据转换为Bytes来存储它。
到目前为止,我已经想出了这个办法。
let data: Bytes = try JSONEncoder().encode(country).base64URLEncodedString()然后,当我从数据库读取记录时,我需要能够逆转这个过程,以便从存储JSON的Bytes中创建我的国家对象。
let mycountry:Country = try decoder.decode(Country.self, from: Data(bytes: DBrecord.value) )struct是:
struct Country: Content {
var country_name: String
var timezone: String
var default_PickUp_location: String = ""
init(country_name: String, timezone:String, default_PickUp_location: String?) {
self.country_name = country_name
self.timezone = timezone
if default_PickUp_location != nil {
self.default_PickUp_location = default_PickUp_location!
}
}
}一个示例JSON是:
{ "country_name" : "Denmark", "timezone" : "Europe\/Copenhagen", "default_pickup_location" : "Copenhagen" }我似乎无法逆转这一转变。有什么帮助吗?
发布于 2018-07-31 14:58:05
在JSON中,使用default_pickup_location,在struct中使用default_PickUp_location。你需要确定一个版本。
为了发现这一点,我使用了以下测试路径:
router.get("json")
{
request throws -> String in
let json = "{ \"country_name\" : \"Denmark\", \"timezone\" : \"Europe/Copenhagen\", \"default_pickup_location\" : \"Copenhagen\" }"
let encoder = try JSONDecoder().decode(Country.self, from: json)
return "It works"
}它返回:
{“错误”:真,“原因”:“键‘默认_拾取_位置’所需的值”}
发布于 2018-07-31 16:47:21
"Bytes“类型声明在哪里,我不认为它是SwiftLang或Foundation。我还记得Data(bytes: Array<UInt>)吗?我猜这是一种编码解码类型的不连续。另外,为了简化您的编码和解码到JSON,您可能会想尝试一下,而不需要快速地处理损坏的Camel情况。
struct Country: Content {
let countryName: String
let timezone: String
let defaultPickupLocation: String
enum CodingKeys: String, CodingKey {
case countryName = "country_name"
case timezone
case defaultPickupLocation = "default_pickup_location"
}
}我还建议您从容器中抓取编码器和解码器,原因是类型一致。例如,如果您的所有JSON都是蛇形案例,您可以更改容器的编码器和解码器,并从上面跳过编码键enum。
var encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase您可以从容器中获取编码器和解码器,如下所示
let contentCoders: ContentCoders = try worker.make()
let jsonEncoder = try contentCoders.requireDataEncoder(for: .json) as? JSONEncoderhttps://stackoverflow.com/questions/51614757
复制相似问题