Nouf
Nouf

Reputation: 773

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"]

    }
}

Upvotes: 2

Views: 1197

Answers (2)

Ryan Romanchuk
Ryan Romanchuk

Reputation: 10869

The comment left by @TarasChernyshenko solves the issue. If you're trying to set a relationship from a nested relationship, make sure you extend Mappable, forgetting this makes it very difficult to debug since you're not going to get any indication or hint about an obvious copy/paste/moving too fast/not enough coffee error.

Upvotes: 0

Muneeb Ali
Muneeb Ali

Reputation: 482

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

Upvotes: 3

Related Questions