我有一个来自服务器的JSON对象:
LOGIN_SUCCESS with JSON: {
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJteS5kb21haW4uY29tIiwic3ViIjoiNTkwOTRkNjRjMmRhN2E3MWI4NTljYTFhIiwiaWF0IjoxNDk0MjY1NTE1LCJleHAiOjE0OTQ4NzAzMTV9.SqsLeToG8-_3CV1Yr4Z4SUIv4-vqGbntGwFLB4i7n-w";
user = {
"__v" = 0;
"_id" = 59094d64c2da7a71b859ca1a;
createdAt = "2017-05-03T03:24:20.309Z";
email = "dylan@msn.com";
name = Dylan;
updatedAt = "2017-05-03T03:24:20.309Z";
};
}
这将作为userInfo转换为字典。但是,由于userinfo中没有返回我的令牌,我如何将其解析为一个类。目前,我的
初始化类似于使用硬编码字符串:
self.loggedInUser.setUser(firstName: "Dylan" as String!,
email: "dylan@msn.com"as String!,
token: "test" as String!,
id: "1"as String!,
longitude: "40.0"as String!,
latitude: "-70"as String!)
self.loggedInUser.printUser()
完全请求尝试:
func loginPost(email: String, password: String, completion: @escaping (_ userInfo: User?, _ error: [[String : Any]]?) -> Void) {
let headers: HTTPHeaders = ["Content-Type" : "application/json"]
let parameters: Parameters = ["email": "\(email)","password": "\(password)"]
Alamofire.request(loginURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.validate(contentType: ["application/json"])
.responseJSON { response in
if response.response?.statusCode == 200 {
print("LOGIN_SUCCESS with JSON: \(response.result.value!)")
if let userInfo = response.value as? [String : Any] {
self.loggedInUser.setUser(firstName: userInfo.["user"]["name"] as! String!,
email: userInfo["email"] as! String!,
token: userInfo["token"] as! String!,
id: "1"as String!,
longitude: "40.0"as String!,
latitude: "-70"as String!)
self.loggedInUser.printUser()
return completion(self.loggedInUser, nil)
}
} else {
print("LOGIN_FAILURE with JSON: \(response.result.value!)")
if let error = response.result.value as? [[String: Any]] {
//If you want array of task id you can try like
return completion(nil, error)
}
}
}
}
最佳答案
请在下面查找更正的代码:
if response.response?.statusCode == 200 {
print("LOGIN_SUCCESS with JSON: \(response.result.value!)")
if let responseData = response.value as? [String : Any] {
let token = responseData["token"] as? String
if let userInfo = responseData as? [String : Any] {
self.loggedInUser.setUser(firstName: userInfo.["user"]["name"] as! String!,
email: userInfo["email"] as! String!,
token: userInfo["token"] as! String!,
id: "1"as String!,
longitude: "40.0"as String!,
latitude: "-70"as String!)
self.loggedInUser.printUser()
return completion(self.loggedInUser, nil)
}
}
}
关于swift - 解析Swift字典的二级,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43854219/