我正在尝试使用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
}
response
fromAlamofire
具有data
可以直接使用的属性:
let json = response.data
do {
let user = try JSONDecoder().decode(UserP.self, from: json)
print(user)
}
catch {
print(error)
}
此外,如果不能保证键nombreUsuario
和empresa
出现在json中,则建议的方法是将这些变量标记为可选。这样,您就不需要自定义解码器逻辑。
struct UserP: Decodable {
var username: String?
var company: String?
private enum CodingKeys: String, CodingKey{
case username = "nombreUsuario"
case company = "empresa"
}
}
如果要提供一些默认值,那么自定义解码器可以帮助您:
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"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句