'ObjectMapper parsing generic object
I got error when parsing generic object with ObjectMapper Here is my classes:
class BaseResponse<T>: NSObject, Mappable {
var isSuccess: Bool!
var data: T?
required init?(map: Map) {
super.init()
self.mapping(map: map)
}
func mapping(map: Map) {
isSuccess <- map["success"]
data <- map["data"]
}
}
class Login: NSObject, Mappable {
var isProfileUpdated: Bool?
var role: String!
var profileId: Int!
var email: String!
override func mapping(map: Map) {
isProfileUpdated <- map["profile_updated"]
role <- map["role"]
profileId <- map["id"]
email <- map["email"]
}
}
I parsed this json:
{
"token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTU4MDkzODAuNjg4LCJpYXQiOjE1MTU3MjI5ODAuNjg4LCJpc3MiOiJleWUtc29sdXRpb24udm4iLCJpZCI6MTgsInJvbGUiOiJlbXBsb3llZSIsInNfaWQiOjg5LCJwX2lkIjoxMX0.v8iEgEXlXGzv5HmDvWs-tUNNYZFBQqCtTLaUkgqXqM0",
"data" : {
"email" : "[email protected]",
"id" : 18,
"profile_updated" : false,
"updated_at" : "2018-01-08T05:51:19.045Z",
"created_at" : "2018-01-08T05:50:51.517Z",
"avatar_id" : null,
"referral_code" : "BFHw6I",
"active" : true,
"role" : "employee",
"referral_id" : null
},
"success" : true
}
via this function:
let response = Mapper<BaseResponse<Login>>().map(JSONString: jsonString)
response.data = nil after parsing. I have no idea. Anyone knows why?
Solution 1:[1]
I found solution:
class BaseResponse<T>: NSObject, Mappable where T: Mappable {
var isSuccess: Bool!
var data: T?
required init?(map: Map) {
super.init()
self.mapping(map: map)
}
func mapping(map: Map) {
isSuccess <- map["success"]
data <- map["data"]
}
}
Everything works fine. Hope this help anyone like me.
Solution 2:[2]
According to their documentation you can just declare T as Mappable. So you'll get something like this:
class BaseResponse<T: Mappable>:Mappable {
var data: T?
required init?(map: Map) {
self.init()
}
func mapping(map: Map) {
data <- map["data"]
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lee5783 |
| Solution 2 | Dmitriy Miyai |
