gpt4 book ai didi

ios - 使用可编码的对象

转载 作者:行者123 更新时间:2023-11-28 05:41:13 25 4
gpt4 key购买 nike

我有一个应用程序,我尝试使用 UserDefaults 在本地保存一个 Codable 模型,但问题是 UserDefault 没有存储所有的Modelvalues 并将 nil 分配给其中一些,有时会分配适当的 value。所以我决定尝试一个替代方案,即 realm 并且我能够修改我的 model 以使用 realm 但我有一个问题不是哪个正在过程解码对象对象使用 Realm 。在使用 List 但非 array Objects 处理 Array object 时,我能够使其工作只是未能映射到JSON

下面是我正在处理的示例数组

{
"id": 732,
"name": "Vendor Name",
"logo": ".../thumb/missing.png",
"kitchens":
{
"id": 36,
"name": "Sandwiches"
}
}

模型类

class VendorsList : Object, Decodable {
@objc dynamic var id : Int = 0
@objc dynamic var name : String?
@objc dynamic var logo : String?
// Create your Realm List.
var kitchensList = List<VendorKitchens>()

override class func primaryKey() -> String? {
return "id"
}

private enum CodingKeys: String, CodingKey {
case id
case name
case logo
// Set JSON Object Key
case kitchensList = "kitchens"

}

public required convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.logo = try container.decode(String.self, forKey: .logo)
// Map your JSON Array response
let kitchens = try container.decodeIfPresent([VendorKitchens].self, forKey: .kitchensList) ?? [VendorKitchens()]
kitchensList.append(objectsIn: kitchens)

}

}


class VendorKitchens : Object, Decodable {
@objc dynamic var id : Int = 0
@objc dynamic var name : String?

override class func primaryKey() -> String? {
return "id"
}

private enum CodingKeys: String, CodingKey {
case id
case name
}
}

返回一个错误

Failed to map data to JSON

最佳答案

来,试试这个。

class VendorsList : Object, Decodable {
@objc dynamic var id : Int = 0
@objc dynamic var name : String?
@objc dynamic var logo : String?
@objc dynamic var kitchens: VendorKitchens? = nil

override class func primaryKey() -> String? {
return "id"
}

private enum CodingKeys: String, CodingKey {
case id
case name
case logo
case kitchens = "kitchens"

}

public required convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.logo = try container.decode(String.self, forKey: .logo)
kitchens = try container.decodeIfPresent(VendorKitchens.self, forKey: .kitchensList)

}

}


class VendorKitchens : Object, Decodable {
@objc dynamic var id : Int = 0
@objc dynamic var name : String?

override class func primaryKey() -> String? {
return "id"
}

private enum CodingKeys: String, CodingKey {
case id
case name
}
}

关于ios - 使用可编码的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56664989/

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