[英]Parsing Failed: JSONDecoder Swift
I'm trying to decode a json request using Alamofire 5.2 The problem is that I use JSONDecoder and I have some issues about the conversion我正在尝试使用 Alamofire 5.2 解码 json 请求问题是我使用 JSONDecoder 并且我有一些关于转换的问题
The API is in Spanish and my models in English so I decided to changed this kind of values using an enum of keys API 是西班牙语,我的模型是英语,所以我决定使用键枚举来更改这种值
But I don't know if this works... Here's my code:但我不知道这是否有效......这是我的代码:
API RESPONSE: (json variable) API 响应:(json 变量)
{
"sistemaOperativoId" : 0,
"nombreUsuario" : "Coasnf_09",
"menus" : [
],
"acciones" : [
],
"fechaRegistro" : "2020-04-15T09:46:24.0573154",
"empresa" : null,
"version" : null
}
MY MODEL:我的 MODEL:
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
}
}
CONVERTION:转换:
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
from Alamofire
has a data
property that you can use directly:来自
Alamofire
的response
有一个可以直接使用的data
属性:
let json = response.data
do {
let user = try JSONDecoder().decode(UserP.self, from: json)
print(user)
}
catch {
print(error)
}
Furthermoe, if the keys nombreUsuario
and empresa
are not guaranteed to come in the json then recommended way is to mark those variables as optional.此外,如果不能保证键
nombreUsuario
和empresa
出现在 json 中,那么推荐的方法是将这些变量标记为可选。 With this you don't need the custom decoder logic.有了这个,您就不需要自定义解码器逻辑。
struct UserP: Decodable {
var username: String?
var company: String?
private enum CodingKeys: String, CodingKey{
case username = "nombreUsuario"
case company = "empresa"
}
}
If you want to give some default values then a custom decoder can help:如果您想提供一些默认值,那么自定义解码器可以提供帮助:
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"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.