Complex Json to Swift Codable



我在尝试"铸造";我对结构的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).

有什么建议吗?我明白我必须改变为!作为Dictionary的数据,但我没有找到任何如何做的例子。

两个致命问题:

  1. 根对象(关键字为datamsg_codemsg_text的字典(缺少

    struct Root: Codable {
    let data : LoginResponse
    }
    
  2. 您必须将responseJSON替换为responseData才能获得原始数据,responseJSON返回Swift数组或字典。

    Alamofire.request("myURL", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseData {
    ...
    case .success(let data):
    let login = try! JSONDecoder().decode(Root.self, from: data)
    

并且不要try!catch错误并处理它。

最新更新