How to model a Swift dictionary property on a Realm object?

Gonzalo

How should I model a dictionary property on a Realm object so when encoded to JSON I can get this:

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

I tried creating a new Object FavoriteThings with 'key' and 'value' properties as I've seen elsewhere...

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

But List gives me an array, naturally, when I encode it to JSON. I don't want an array. I'm using Swift Codable.

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

Any pointers appreciated!

Gonzalo

Rob

As you know, Lists are encoded into json arrays by default. So, to encode a List into a Dictionary you'll have to implement a custom encode method to do exactly that.

public class FavoriteThings: Object {
    @objc dynamic var key = ""
    @objc dynamic var value = ""

    convenience init(key: String, value: String) {
        self.init()
        self.key = key
        self.value = value
    }
}

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)
    }
}

And the usage would be like this:

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)
    }
}

Which prints:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Swift Realm Property '*' has been added to latest object model MIGRATION

How to delete object in realm in Swift

how to update an object in realm swift

How to persist a Realm List property in Swift 4?

How to set primary key in Swift for Realm model

How to add new property to a Realm Object?

How to filter object from Realm database in Swift

Store nested model object with list in Realm swift4

Update model Realm Swift

How to convert a Swift object to a dictionary

Realm model object method

Using enum as property of Realm model

How to sort dictionary by object property vbscript

How to retrieve an object that is in a list in another object using realm swift?

Issue in Realm List to [Model] in swift

Realm: sorting by property in child object

How to check if an object is dictionary or not in swift 3?

How to get the index of a specific object in Dictionary in swift

How to Map Object / Class Property to Dictionary When Object Property And Dictionary Key Names Are Different?

How can I filter by specific date from realm object in swift?

Realm Swift how to add observer to object type (nil)

How can I convert a Realm object to JSON in Swift?

How can I add or update a Realm object in Swift?

realm swift . How to link to exist object with primary key

Transform a dictionary into an object model

Realm Object returning nil (Swift)

How to use NOT IN with Realm Swift

How to decode a property with type of JSON dictionary in Swift 4 decodable protocol

How to decode a property with type of JSON dictionary in Swift [45] decodable protocol

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive