如何在 Swift 5 中解析来自 Alamofire 的模型结构的 JSON 响应?
How to parse JSON response to Model struct from Alamofire in Swift 5?
我尝试使用 Alamofire post mysql 数据库,我成功了,但我的响应似乎不是 json,我想将响应值传递给模型结构。我试过这段代码。哪里错了?
如果您能提供帮助,我将不胜感激。
func register(registerModel:RegisterResponse,completion:@escaping (RegisterModel?)->() ){
let parameters: [String: Any] =
[
"email": "\(registerModel.email)",
"password": "\(registerModel.password)",
"first_name": "\(registerModel.first_name)",
"last_name": "\(registerModel.last_name)",
]
AF.request(registerUrl,method: .post,parameters: parameters,encoding: URLEncoding.httpBody,headers: nil).responseJSON(){ response in
//debugPrint(response)
switch response.result{
case .success(let data):
if response.data != nil {
print(data)
completion(data as? RegisterModel)
}
case .failure(let err):
print(err.localizedDescription)
}
}
}
输出:
{
result = "account already exists";
tf = 0;
verificationCode = "<null>";
}
试试这个
AF.request(registerUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { (response) in
print(response)
}
假设您的 RegisterResponse
是 Decodable
,只需使用 responseDecodable
:
AF.request(registerUrl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
.responseDecodable(of: RegisterResponse.self) { response in
// Handle response.
}
我尝试使用 Alamofire post mysql 数据库,我成功了,但我的响应似乎不是 json,我想将响应值传递给模型结构。我试过这段代码。哪里错了? 如果您能提供帮助,我将不胜感激。
func register(registerModel:RegisterResponse,completion:@escaping (RegisterModel?)->() ){
let parameters: [String: Any] =
[
"email": "\(registerModel.email)",
"password": "\(registerModel.password)",
"first_name": "\(registerModel.first_name)",
"last_name": "\(registerModel.last_name)",
]
AF.request(registerUrl,method: .post,parameters: parameters,encoding: URLEncoding.httpBody,headers: nil).responseJSON(){ response in
//debugPrint(response)
switch response.result{
case .success(let data):
if response.data != nil {
print(data)
completion(data as? RegisterModel)
}
case .failure(let err):
print(err.localizedDescription)
}
}
}
输出:
{
result = "account already exists";
tf = 0;
verificationCode = "<null>";
}
试试这个
AF.request(registerUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { (response) in
print(response)
}
假设您的 RegisterResponse
是 Decodable
,只需使用 responseDecodable
:
AF.request(registerUrl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
.responseDecodable(of: RegisterResponse.self) { response in
// Handle response.
}