微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

复杂的Json到Swift Codable

如何解决复杂的Json到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).

有什么建议吗?我知道我必须改变为!作为字典的数据,但是我没有找到任何示例。

解决方法

两个致命问题:

  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错误并进行处理。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。