gpt4 book ai didi

json - ObjectMapper 解析通用对象

转载 作者:行者123 更新时间:2023-12-02 17:12:47 27 4
gpt4 key购买 nike

使用 ObjectMapper 解析通用对象时出现错误这是我的类(class):

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。我不知道。谁知道为什么?

最佳答案

我找到了解决方案:

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

一切正常。希望这对像我这样的人有所帮助。

关于json - ObjectMapper 解析通用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48218652/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com