【发布时间】:2021-01-18 12:17:34
【问题描述】:
我在尝试将我的 JSON 响应“转换”到我的结构时遇到了问题。
我的 JSON 响应:
{
"data" = {
"answers" = {
"10" = "Not";
"11" = "Not";
};
"company" = 1;
"name" = "Name";
"profile" = {
"email" = "email@email.com";
"first_name" = "First name";
"identity_document" = 12345678;
};
};
"msg_code" = 0;
"msg_text" = "Success";
}
我的结构:
struct LoginResponse: Codable {
let answers: Dictionary<String, String>?
let company: Int?
let name: String?
let profile: Profile?
private enum CodingKeys: String, CodingKey{
case answers = "answers"
case company = "company"
case name = "name"
case profile = "profile"
}
}
struct Profile: Codable{
let email: String?
let first_name: String?
let identity_document: String?
private enum CodingKeys: String, CodingKey{
case email = "email"
case first_name = "first_name"
case identity_document = "identity_document"
}
}
我要解码的代码:
Alamofire.request("myURL", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON{
response in
switch response.result
{
case .success(let json):
let login = try! JSONDecoder().decode(LoginResponse.self, from: json as! Data)
SVProgressHUD.dismiss()
case .failure(let error):
self.showAlertOk(title:"Alert!", message: "Response Error", handlerOK: { action in print("error")})
SVProgressHUD.dismiss()
}
}
行:
let login = try! JSONDecoder().decode(LoginResponse.self, from: json as! Data)
这是修复之前版本的结果:
let login = try! JSONDecoder().decode(LoginResponse.self, from: json)
或
let login = try! JSONDecoder().decode(LoginResponse.self, from: json.data(using: .utf8)!)
logcat 说,
Could not cast value of type '__NSDictionaryI' (0x7fff87b9d5f0) to 'NSData' (0x7fff87b9c088).
有什么建议吗?我明白我必须改变为!作为字典的数据,但我没有找到任何示例。
【问题讨论】:
标签: swift encode codable decodable jsondecoder