Objectmapper: Can't convert type string to an Int type

Created on 6 Aug 2016  路  2Comments  路  Source: tristanhimmelman/ObjectMapper

public final class CategoryResponseCategoryModel: Mappable {
    var catId:String?
    var catName:String?
    var parentId:String?
    var sortOrder:String?
    var level:String?
    var mobileCatPic:String?
    var catUrl:String?
    var subCategory:[CategoryResponseCategoryModel]?
    var catIds:Int = NSNotFound

    required public init?(_ map: Map) {

    }
    public func mapping(map: Map) {
        catId <- map["cat_id"]
        catName <- map["cat_name"]
        parentId <- (map["parent_id"])
        sortOrder <- map["sort_order"]
        level <- map["level"]
        mobileCatPic <- map["mobile_cat_pic"]
        catUrl <- map["cat_url"]
        catIds <- map["cat_id"]
    }
}

catID = 11241 why catIds = NSNotFound

Below is a picture

qq20160806-0

Most helpful comment

cat_id is a string in the JSON response so you cannot automatically convert it to an Int.

You need to use a transform to achieve this... something like this

catIds <- (map["cat_id"], TransformOf<Int, String>(fromJSON: { $0 == nil ? nil : Int($0!) }, toJSON: { $0.map { String($0) } }))

There are examples in the test files

All 2 comments

cat_id is a string in the JSON response so you cannot automatically convert it to an Int.

You need to use a transform to achieve this... something like this

catIds <- (map["cat_id"], TransformOf<Int, String>(fromJSON: { $0 == nil ? nil : Int($0!) }, toJSON: { $0.map { String($0) } }))

There are examples in the test files

Thanks

Was this page helpful?
0 / 5 - 0 ratings