【发布时间】:2017-12-14 15:35:40
【问题描述】:
我必须用来自 Restful API 的数据填充模型。在我的代码中,我以这种方式反序列化我的 JSON:
func DoLogin(_ user:String, _ psw:String)
{
let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/auth")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let paramToSend = "username=" + user + "&password=" + psw
request.httpBody = paramToSend.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data else
{
return
}
let json:AnyObject?
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
let userInfo = parseJSON["userInfo"] as! NSDictionary
self.loginModel.firstNames = userInfo["firstNames"] as! String
self.loginModel.lastNames = userInfo["lastNames"] as! String
self.loginModel.claroClubPoints = userInfo["claroClubPoints"] as! Int
self.loginModel.imageProfileUrl = userInfo["imageProfileUrl"] as! String
let mainProductService = parseJSON["mainProductService"] as! NSDictionary
self.loginModel.idProductService = mainProductService["idProductService"] as! Int
self.loginModel.lineType = mainProductService["lineType"] as! Int
self.loginModel.lineName = mainProductService["lineName"] as! String
self.loginModel.lineAlias = mainProductService["lineAlias"] as! String
self.loginModel.profileType = mainProductService["profileType"] as! Int
self.loginModel.idAccount = mainProductService["idAccount"] as! Int
self.loginModel.idReceipt = mainProductService["idReceipt"] as! Int
self.loginModel.category = mainProductService["category"] as! Int
self.loginModel.clientType = mainProductService["clientType"] as! Int
let userData = parseJSON["userData"] as! NSDictionary
self.loginModel.userClientType = userData["clientType"] as! Int
self.loginModel.docType = userData["docType"] as! Int
self.loginModel.docNum = userData["docNum"] as! Int
self.loginModel.email = userData["email"] as! String
self.loginModel.msisdn = userData["msisdn"] as! Int
let defaultServiceResponse = parseJSON["defaultServiceResponse"] as! NSDictionary
self.loginModel.idTransaction = defaultServiceResponse["idTransaction"] as! String
self.loginModel.message = defaultServiceResponse["message"] as! String
self.loginModel.idResponse = defaultServiceResponse["idResponse"] as! Int
}
} catch {
let error = ErrorModel()
error.phrase = "PARSER_ERROR"
error.code = -1
error.desc = "Parser error in login action"
}
})
task.resume()
}
但我真的不知道我做错了什么,因为我的 LoginModel 的结果完全是空的。我是否以错误的方式传递数据?
【问题讨论】:
-
放置断点并检查代码流。
-
你知道你是不是在获取数据但是JSON解析错误?或者您根本没有获取数据?
-
我没有得到数据!