ObjectMapper解析通用对象

时间:2018-01-12 02:19:12

标签: json swift objectmapper

使用ObjectMapper解析通用对象时出错 这是我的课程:

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"]
    }
}

我解析了这个json:

{
     "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTU4MDkzODAuNjg4LCJpYXQiOjE1MTU3MjI5ODAuNjg4LCJpc3MiOiJleWUtc29sdXRpb24udm4iLCJpZCI6MTgsInJvbGUiOiJlbXBsb3llZSIsInNfaWQiOjg5LCJwX2lkIjoxMX0.v8iEgEXlXGzv5HmDvWs-tUNNYZFBQqCtTLaUkgqXqM0",
     "data" : {
        "email" : "at.ce90@gmail.com",
        "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
}

通过此功能:

let response = Mapper<BaseResponse<Login>>().map(JSONString: jsonString)
解析后,

response.data = nil。我不知道。谁知道为什么?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

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"]
    }
}

一切正常。希望这能帮到像我这样的人。