Search code examples
swiftalamofireobjectmapper

Using Alamofire and Objectmapper the integer value always zero


I am using Alamofire with ObjectMapper and my model class is like that

class Category: Object, Mappable {

dynamic var id: Int = 0
dynamic var name = ""
dynamic var thumbnail = ""
var children = List<Category>()


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


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

func mapping(map: Map) {
    id <- map["id"]
    name <- map["name"]
    thumbnail <- map["thumbnail"]
    children <- map["children"]
}

}

and I am using Alamofire like that

 Alamofire.request(.GET, url).responseArray { (response: Response<[Category], NSError>) in

        let categories = response.result.value

        if let categories = categories {
            for category in categories {
                print(category.id)
                print(category.name)
            }
        }
    }

the id is always zero, I don't know why?


Solution

  • Does the "id" field exist in the JSON file? If it does not, your initial value of zero will remain. Is the value in quotes in the JSON file? If it is, then it's a string. I don't know if ObjectMapper will convert it to Int.

    Moved my comment to an answer.