如何在Realm对象上建模Swift字典属性?

问题描述 投票:0回答:1

我应该如何在Realm对象上为字典属性建模,因此当编码为JSON时,我可以得到以下信息:{“ firstName”:“ John”,“ lastName”:“ Doe”,“最喜欢的东西”: {“ car”:“ Audi R8”,“水果”:“草莓”“ tree”:“橡树”}}

[我尝试在其他地方看到的具有'key'和'value'属性的新对象FavoriteThings ...

public class Person: Object {
    @objc dynamic var firstName = ""
    @objc dynamic var lastName = ""
    var favoriteThings = List<FavoriteThings>()
}

但是当我将其编码为JSON时,List自然会给我一个数组。我不要数组。我正在使用Swift Codable。

{
    "firstName": "John",
    "lastName": "Doe",
    "favoriteThings": [
    {
      "key": "fruit",
      "value": "strawberries"
    },
    {
      "key": "tree",
      "value": "Oak"
    }
    ],
}

感谢任何指针!

贡萨洛

swift realm-mobile-platform realm-list
1个回答
0
投票

您将不得不编写一个自定义编码方法:

public class Person: Object, Encodable {

    enum CodingKeys: String, CodingKey {
        case firstName
        case lastName
        case favoriteThings
    }

    @objc dynamic var firstName = ""
    @objc dynamic var lastName = ""
    let favoriteThings = List<FavoriteThings>()

    convenience init(firstName: String, lastName: String, favoriteThings: [FavoriteThings]) {
        self.init()
        self.firstName = firstName
        self.lastName = lastName
        self.favoriteThings.append(objectsIn: favoriteThings)
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(firstName, forKey: .firstName)
        try container.encode(lastName, forKey: .lastName)

        var favThings: [String: String] = [:]
        for thing in favoriteThings {
            favThings[thing.key] = thing.value
        }

        try container.encode(favThings, forKey: .favoriteThings)
    }
}

用法将是这样的:

func testEncode() {
    let john = Person(
        firstName: "John",
        lastName: "Doe",
        favoriteThings: [
            .init(key: "car", value: "Audi R8"),
            .init(key: "fruit", value: "strawberries"),
            .init(key: "tree", value: "Oak"),
    ])

    let encoder = JSONEncoder()
    let data = try! encoder.encode(john)
    if let string = String(data: data, encoding: .utf8) {
        print(string)
    }
}

哪些印刷品:

{"firstName":"John","favoriteThings":{"car":"Audi R8","fruit":"strawberries","tree":"Oak"},"lastName":"Doe"}

© www.soinside.com 2019 - 2024. All rights reserved.