Mapping Nested JSON Realm object in swift

I have is using Realm and Alamofire to get and store my data , but I got this one object which is a nested JSON object I am trying to access the Address but I get nil I am able to get the content data but not the address

"content": [ { "id": 1, "fisrtname": "Names", "lastname": "last" "Address": { "id": 1, "city": "city", "phone": null, "street": "city", }

class Name: Object, Mappable {
@objc dynamic var id: Int = 0
@objc dynamic var fisrtname: String? = ""
@objc dynamic var lastname: String? = ""
@objc dynamic var Address: Address? = nil
override static func primaryKey() -> String? {
    return "id"
}

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

func mapping(map: Map) {
    id <- map["id"]
    fisrtname <- map["fisrtname"]
    lastname <- map["lastname"]
    Address <- map["Address"]
}

class Address: Object {
    @objc dynamic var id: Int = 0
    @objc dynamic var city: String? = ""
    @objc dynamic var phone: Int? = ""
    @objc dynamic var street: String? = ""

    override static func primaryKey() -> String? {
        return "id"
    }

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

    func mapping(map: Map) {
        id <- map["id"]
        city <- map["city"]
        phone <- map["phone"]
        street <- map["street"]

    }
}

1 answer

  • answered 2018-11-08 07:44 Muneeb ali

    Try to make model like this

    import Foundation
    import RealmSwift
    
        class Name: Object {
            dynamic var id = 0
            dynamic var fisrtname : String?
            dynamic var lastname : String?
            dynamic var Address : UserAddress? = UserAddress()
    
            override static func primaryKey() -> String? {
                return "id"
            }
        }
    
    
        class UserAddress: Object {
    
            dynamic var id = 0
            dynamic var city : String?
            dynamic var phone : String?
            dynamic var street : String?
    
            override static func primaryKey() -> String? {
                return "Id"
            }
        }
    

    And To get address from Json :

    let responseResult = result["Result"] as! NSDictionary
    let name = Name(value: responseResult)
    let address = name.Address?.city