【发布时间】:2020-04-17 18:53:33
【问题描述】:
我正在尝试使用 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
}
【问题讨论】:
-
什么是
User?json设置在哪里?为什么你同时使用JSONSerialization和JSONDecoder? -
print("Parsing Failed: ", error.localizedDescription)=> ùprint("解析失败:",错误) -
@Larme “解析失败:No se pudo leer los datos porque no se encontraron。”
-
然后显示获得
json的代码。编码为字符串,然后解码为UserP似乎是多余的 - 为什么不能简单地将获得的 JSON 数据传递给JSONDecoder.decode()? -
如果
nombreUsuario和empresa不保证进入 json 那么它应该是可选的,然后你的解码器应该有类似company = try container.decodeIfPresent(String.self, forKey: .company)的东西
标签: json swift decode jsonresponse