我想做:
JSONDecoder()
,我将json
转换为Realm
对象。Realm
个数据库。问题:
RLMArray
不适用Codable
协议。Decodable
协议,但Codable
我不能。错误讯息:
代码:
public class Hobby: Object, Codable {
@objc dynamic var title: String?
@objc dynamic var category: String?
}
public class Person: Object, Codable { // Error: Type 'Person' does not conform to protocol 'Encodable'
@objc dynamic var name: String?
@objc dynamic var hobbies: RLMArray<Hobby>?
required convenience public init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
hobbies = try container.decode(RLMArray<Hobby>?.self, forKey: .hobbies)
}
}
func sample() {
let person = try? JSONDecoder().decode(Person.self, from: "{\"name\" : \"aaa\",\"hobbies\" : [{\"title\" : \"fishing\",\"category\" : \"outdoor\"},{\"title\" : \"reading\",\"type\" : \"indoor\"}]}".data(using: .utf8)!)
print(person)
let realm = try! Realm()
try! realm.write {
realm.add(person!)
}
}
你有什么想法吗?
Swift4 RealmSwift
答案 0 :(得分:2)
Codable与Decodable + Encodable完全相同。如果你想要符合Codable,你需要实现编码函数,对于你的Person对象将是:
enum CodingKeys: String, CodingKey {
case name
case hobbies
// or: case hobbies = "customHobbiesKey" if you want to encode to a different key
}
func encode(to encoder: Encoder) throws {
do {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(hobbies, forKey: .hobbies)
} catch {
print(error)
}
}
将此添加到您的Person类,然后为您的Hobby类实现相同的功能。
因为我不确定你是否想要编码:如果您需要做的只是从Json创建Realm-Objects,我只需将'Codable'替换为'Decodable'-Protocol。
编辑:我注意到问题与RLMArray有关。我不确定可编码如何与RLMArray一起使用,但是如果它不起作用你可以尝试用替换声明 let hobbies = List<Hobby>()
然后在init()中将'hobbies'行替换为:
let tempHobbyList: [Hobby] = try container.decode([Hobby].self, forKey: .hobbies)
self.hobbies.append(objectsIn: tempHobbyList)
这就是我用realmObjects获取我的列表以使用可编码的
的方法