Search code examples
iosswiftrealmobjectmapper

Model from JSON containing Array and Dictionary


class AppUsers: Object{
    dynamic var email: String = ""
    dynamic var type: String = ""

    required convenience init?(map: Map) {
        self.init()
        mapping(map: map)
    }

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

        extension AppUsers : Mappable {

            func mapping(map: Map) {
                email               <- map["email"]
        //        active_platforms    <- map["active_platforms"]
                type                <- map["type"]
        //        linked_to           <- map["linked_to"]
            }
        }

JSON RESPONSE:

{
       "email": "asd@gmail.com",
       "type": "primary_email",
       "linked_to": {
         "_id": "DAS44564dasdDASd",
         "image": null,
         "company": null,
         "designation": null,
         "name": null
       },
       "active_platforms": [
         "asd",
         "qwe"
       ]
     }

From above response how to get linked_to which is a Dictionary and active_platforms which is an Array. I tried creating separate class for linked_to create var of it in AppUsers but it didn't helped.


Solution

  • A one to one relationship is

    dynmamic var linkedTo: LinkObject?
    

    A one to many relationship is

    let activePlatforms = List<ActivePlatform>()
    

    If you want to use object mapper to fill them, LinkObject must be mappable and ActivePlatform must be mappable AND you must supply a custom transform to convert the JSON array into a Realm List.