解析失败:JSONDecoder Swift

Parsing Failed: JSONDecoder Swift

我正在尝试使用 Alamofire 5.2 解码 json 请求 问题是我使用 JSONDecoder 并且我有一些关于转换的问题

API 是西班牙语,而我的模型是英语,所以我决定使用键枚举来更改这种值

但我不知道这是否有效...这是我的代码:

API 响应:(json 变量)

    {
  "sistemaOperativoId" : 0,
  "nombreUsuario" : "Coasnf_09",
  "menus" : [

  ],
  "acciones" : [

  ],
  "fechaRegistro" : "2020-04-15T09:46:24.0573154",
  "empresa" : null,
  "version" : null
}

我的模特:

struct UserP: Decodable{
    var username : String
    var company : String

    private enum CodingKeys: String, CodingKey{
        case username = "nombreUsuario"
        case company = "empresa"
    }

    init(from decoder: Decoder) throws{
        let container = try decoder.container(keyedBy: CodingKeys.self)
        username = try container.decode(String.self, forKey: .username) ?? "null"
        company = try container.decode(String.self, forKey: .company)  ?? "null"
    }

    init(username: String, company: String){
        self.username = username
        self.company = company
    }
}

转化率:

   func login(user: User) -> UserP? {
        var userData: UserP! = nil
        AF.request(UserRouter.login(user: user)).responseJSON{ response in
            switch response.result {
            case .success(let response):
                print(response)
                let dict = (response as? [String : Any])!
                let json = dict["data"] as! [String: Any]

                if let jsonData = try? JSONSerialization.data(withJSONObject: json , options: .prettyPrinted)
                {
                    do {
                        var jsonString = String(data: jsonData, encoding: String.Encoding.utf8)!
                        print(jsonString)
                        userData = try JSONDecoder().decode(UserP.self, from: Data(jsonString.utf8))
                        print("Object Converted: ", userData.username)
                    } catch {
                        print("Parsing Failed: ", error.localizedDescription)
                    }
                }



                break

            case .failure(let error):
                print(error)
                break
            }
        }

        return userData
    }

Alamofire 逻辑相关更改:

response 来自 Alamofire 有一个 data 属性 可以直接使用:

let json = response.data
do {
    let user = try JSONDecoder().decode(UserP.self, from: json)
    print(user)
}
catch {
    print(error)
}

此外,如果 nombreUsuarioempresa 键不能保证出现在 json 中,那么推荐的方法是将这些变量标记为可选。有了这个,您就不需要自定义解码器逻辑了。

模型更改 #1:

struct UserP: Decodable {
    var username: String?
    var company: String?

    private enum CodingKeys: String, CodingKey{
        case username = "nombreUsuario"
        case company = "empresa"
    }
}

模型更改 #2:

如果您想提供一些默认值,那么自定义解码器可以提供帮助:

struct UserP: Decodable {
    var username: String
    var company: String

    private enum CodingKeys: String, CodingKey{
        case username = "nombreUsuario"
        case company = "empresa"
    }

    init(from decoder: Decoder) throws{
        let container = try decoder.container(keyedBy: CodingKeys.self)
        username = try container.decodeIfPresent(String.self, forKey: .username) ?? "Default Name"
        company = try container.decodeIfPresent(String.self, forKey: .company) ?? "Default Company Name"
    }
}