Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 299
Ayman Avatar asked Jul 20 '26 05:07

Ayman


2 Answers

I fixed it by adding transformation in the mapping function in model class like that

id <- (map["id"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))

thanks to @BobWakefield

like image 89
Ayman Avatar answered Jul 23 '26 12:07

Ayman


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.

like image 34
Bob Wakefield Avatar answered Jul 23 '26 13:07

Bob Wakefield