本文介绍了如何快速在模型中存储 JSON 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经为 loginviewcontroller 响应创建了模型
I have created model for loginviewcontroller response
我收到如下响应,如何在 loginviewcontroller 中向此模式添加值.. 我收到此响应的位置
I am getting response like below, how to add values to this mode in loginviewcontroller.. where i am getting this response
struct Employees: Codable {
let jsonrpc: String
let result: Result
}
// MARK: - Result
struct Result: Codable {
let userdata: Userdata
let token: String
}
// MARK: - Userdata
struct Userdata: Codable {
let id: Int
let fname, lname, email: String
.......
}
loginviewcontroller APICall:
loginviewcontroller APICall:
func loginService(){
let url = URL(string: "https://apkool.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let jsonpost = LoginData(jsonrpc: "2.0", params: (PostLogin(email: nameTf.text!, password: passwordTf.text!, device_id: "2")))
do {
let jsonBody = try JSONEncoder().encode(jsonpost)
request.httpBody = jsonBody
} catch {
print("Error while encoding parameter: \(error)")
}
let session = URLSession.shared
let task = session.dataTask(with: request) { [self] (data, response, error) in
guard let data = data else {return}
do{
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
print("the json output \(String(describing: json))")
let error = json!["error"] as? [String : Any]
let status = error?["status"] as? [String : Any]
DispatchQueue.main.sync{
if error != nil{
let controller = UIAlertController(title: "Alert", message: "Your email is not verified", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
controller.addAction(ok)
controller.addAction(cancel)
self.present(controller, animated: true, completion: nil)
}
else{
let res = json?["result"] as? [String : Any]
let uData = res?["userdata"] as? [String : Any]
var nameLogin = uData?["slug"] as? String
var emailLogin = uData?["email"] as? String
print("login name \(String(describing: nameLogin))")
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProfileViewController1") as? ProfileViewController1
vc?.name = nameLogin
vc?.email = emailLogin
self.navigationController?.pushViewController(vc!, animated: true)
}
}
print("the error is \(error)")
}catch{ print("Error while decoding: \(error.localizedDescription)") }
}
task.resume()
}
我想向模型添加登录响应,以便在另一个视图控制器中使用这些值..请帮忙..我被困在这里很久了
i want to add login response to model to use these values in another viewcontroller.. pls do help.. i got stuck here from long time
对于上述 api,我收到登录响应:
for above api i am getting response for login:
{
"jsonrpc": "2.0",
"result": {
"userdata": {
"id": 47,
"fname": "sample",
"lname": "test",
"last_login": "2021-02-23 15:04:56",
"created_at": "2021-02-17 20:22:49",
"updated_at": "2021-02-23 15:04:56",
"deleted_at": null
},
"devicetoken": fasfcsdfdsfsdfsd
}
}
推荐答案
因为您可能会从服务器收到这样的错误:
Since you may get an error from the server like so:
{
"jsonrpc": "2.0",
"error": {
"status": {
"code": "-32706",
"message": "Not Verified",
"meaning": "Your email is not verified."
}
}
}
改变你的模型:
struct Employees: Codable {
let jsonrpc:String
let result:Result?
let error:ResponseError?
}
struct ResponseError:Codable {
let status:ErrorStatus
}
struct ErrorStatus:Codable {
let code:String?
let message:String?
let meaning:String?
}
// MARK: - Result
struct Result: Codable {
let userdata: Userdata
let token: String
}
// MARK: - Userdata
struct Userdata: Codable {
let id: Int
let fname, lname, slug, email: String
......
//IMPORTANT: MAKE SURE YOUR CONSTANT NAMES ARE EXACTLY THE SAME AS YOUR
//RESPONSE, OTHERWISE YOU MUST ADD AN ENUM like so:
private enum CodingKeys: String, CodingKey {
case firstName = "fname"
}
然后在你的 api
func loginService(){
let url = URL(string: "https://appleskool.com/preview/appleskool_code/api/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let jsonpost = LoginData(jsonrpc: "2.0", params: (PostLogin(email: nameTf.text!, password: passwordTf.text!, device_id: "2")))
let session = URLSession.shared
let task = session.dataTask(with: request) { [self] (data, response, error) in
guard let data = data else {return}
let decoder = JSONDecoder()
guard let employees = try? decoder.decode(Employees.self, from: data) else { return }
//then you can access your result
if let error = employees.error {
//use your error
print(error.status.message)
print(error.status.meaning)
}else{
//use your data
guard let user = employees.result else {return }
print(user.userdata.fname)
print(user.userdata.lname)
print(user.userdata.email)
print(user.userdata.slug)
// or your can do what you already doing in your code
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProfileViewController1") as? ProfileViewController1
vc?.name = ser.userdata.fname
vc?.lastName = ser.userdata.lname
//if you want to pass the token
vc?.token = user.token
self.navigationController?.pushViewController(vc!, animated: true)
// etc
}
}
task.resume()
}
这篇关于如何快速在模型中存储 JSON 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!