Steven.L Steven.L - 1 year ago 97
Swift Question

How to map different type using ObjectMapper?

I'm using ObjectMapper to map my JSON to Swift object.

I have the following Swift object:

class User: Mappable {

var name: String?
var val: Int?

required init?(map: Map) { }

func mapping(map: Map) {
name <- map["name"]
val <- map["userId"]
}
}


I have this JSON structure:

{
"name": "first",
"userId": "1" // here is `String` type.
},
{
"name": "second",
"userId": 1 // here is `Int` type.
}


After mapping the JSON, the
userId
of
User
which
name
is
"first"
is null.

How can I map
Int/String
to
Int
?

Answer Source

You should improve your API. However, if you can't do that, then try this code:

class User: Mappable {

    var name: String?
    var val: Int?

    required init?(map: Map) { }

    func mapping(map: Map) {
        name <- map["name"]

        // 1: Get the value of JSON and store it in a variable of type Any?
        var userIdData: Any?
        userIdData <- map["userId"]

        // 2: Check the value type of the value and convert to Int type
        if userIdData is Int {
            val = (userIdData as! Int) 
        } else if userIdData is String {
            val = Int(userIdData as! String) 
        }
    }
}

You can refer to this document: Type Casting

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download