如何对Realm的List<>进行编码类型 [英] How to encode Realm's List<> type

查看:96
本文介绍了如何对Realm的List<>进行编码类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Realm数据库编码为JSON.除List<>编码外,其他所有功能均正常工作.所以我的问题是,您将如何编码List<>?因为List不符合 Encodable 可增强的 Decodable 协议.

I am trying to encode my Realm database to JSON. Everything is working except the List<> encoding. So my question is, how would you encode List<>? Because the List doesn't conform to Encodable neighter Decodable protocol.

现在我正在这样做:

@objcMembers class User: Object, Codable{
    dynamic var name: String = ""
    let dogs = List<Dog>()


    private enum UserCodingKeys: String, CodingKey {
        case name
        case dogs
    }

    convenience init(name: String) {
        self.init()
        self.name = name
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: UserCodingKeys.self)
        try container.encode(name, forKey: .name)

    }



@objcMembers class Dog: Object, Codable{
    dynamic var name: String = ""
    dynamic var user: User? = nil

    private enum DogCodingKeys: String, CodingKey {
        case name
    }

    convenience init(name: String) {
        self.init()
        name = name
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: DogCodingKeys.self)
        try container.encode(name, forKey: .name)

    }
}

这样,我正在尝试做到这一点:

and like this I am trying to do it:

var json: Any?
let user = RealmService.shared.getUsers()
var usersArray = [User]()
for user in users{
     usersArray.append(user)
}

let jsonEncoder = JSONEncoder()
let jsonDecoder = JSONDecoder()
let encodedJson = try? jsonEncoder.encode(portfoliosArray)


        if let data = encodedJson {
            json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
            if let json = json {
                print(String(describing: json))
            }
        }

所以问题是我如何编码List<Dog>?

So the question is how I am able to encode the List<Dog>?

推荐答案

要使具有List类型的属性的Realm对象模型类符合Encodable,只需将List转换为encode(to:)方法中,该方法可以自动进行编码.

To make a Realm object model class with a property of type List conform to Encodable, you can simply convert the List to an Array in the encode(to:) method, which can be encoded automatically.

extension User: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(self.username, forKey: .username)
        let dogsArray = Array(self.dogs)
        try container.encode(dogsArray, forKey: .dogs)
    }
}

我使用的测试类(与问题中的类稍有不同,但是我手头已经有这些类,并且无论变量名如何,所讨论的方法几乎都是相同的)

Test classes I used (slightly different from the ones in your question, but I already had these on hand and the methods in question will be almost identical regardless of the variable names):

class Dog: Object,Codable {
    @objc dynamic var id:Int = 0
    @objc dynamic var name:String = ""
}

class User: Object, Decodable {
    @objc dynamic var id:Int = 0
    @objc dynamic var username:String = ""
    @objc dynamic var email:String = ""
    let dogs = List<Dog>()

    private enum CodingKeys: String, CodingKey {
        case id, username, email, dogs
    }

    required convenience init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        username = try container.decode(String.self, forKey: .username)
        email = try container.decode(String.self, forKey: .email)
        let dogsArray = try container.decode([Dog].self, forKey: .dogs)
        dogs.append(objectsIn: dogsArray)
    }
}

测试编码/解码:

let userJSON = """
{
    "id":1,
    "username":"John",
    "email":"example@ex.com",
    "dogs":[
        {"id":2,"name":"King"},
        {"id":3,"name":"Kong"}
    ]
}
"""

do {
    let decodedUser = try JSONDecoder().decode(User.self, from: userJSON.data(using: .utf8)!)
    let encodedUser = try JSONEncoder().encode(decodedUser)
    print(String(data: encodedUser, encoding: .utf8)!)
} catch {
    print(error)
}

输出:

{"username":"John","dogs":[{"id":2,"name":"King"},{"id":3,"name":"Kong"}]}}

{"username":"John","dogs":[{"id":2,"name":"King"},{"id":3,"name":"Kong"}]}

这篇关于如何对Realm的List&lt;&gt;进行编码类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆