3

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?

Ayman
  • 175
  • 1
  • 13
  • 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. – Bob Wakefield Jan 31 '16 at 20:45
  • yes "id" exists in JSON file – Ayman Feb 01 '16 at 08:51
  • you are right the value of "id" in quotes in JSON file if I removed the quotes it can map the value. Thanks @BobWakefield – Ayman Feb 01 '16 at 09:42

2 Answers2

10

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

Ayman
  • 175
  • 1
  • 13
3

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.

Bob Wakefield
  • 814
  • 9
  • 16