当传入的JSON与数据类型不匹配时,JSONDecoder.decode方法不会引发错误。
我有一个像这样的数据模型,它将JSON映射到用户个人资料:
struct DrivetimeUserProfile: Codable {
var driverId: String?
var name: String?
var email: String?
var phoneNumber: String?
var city: String?
var state: String?
var experience: Int?
private enum CodingKeys: String, CodingKey {
case driverId = "driver_id"
case name = "name"
case email = "email"
case phoneNumber = "phone"
case city = "city"
case state = "state"
case experience = "experience"
}
}
如果用户名或密码不正确,服务器将返回类似\"Failure\":\"Enter correct username and password.\"
的JSON。不会映射到用户配置文件数据模型和JSONDecoder()。decode不会引发错误
这是完整的实现:
func loginUser(from url: URL, with username: String, and password: String, completionHandler: @escaping (DrivetimeUserProfile?, DrivetimeAPIError.LoginError?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = cachePolicy
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let query = "email=\(username)&password=\(password)"
request.httpBody = query.data(using: .utf8)
let task = session.dataTask(with: request) { (data, response, error) in
guard let data = data else {
completionHandler(nil, .EmptyData)
return
}
do {
let userProfile = try JSONDecoder().decode(DrivetimeUserProfile.self, from: data)
self.userProfile = userProfile
completionHandler(userProfile, nil)
} catch (let error) {
completionHandler(nil, .CannotDecodeJson)
}
}
task.resume()
}
我需要此完成处理程序来捕获引发的错误,以便可以在我的视图控制器中向用户警告错误是什么。请指教
谢谢
答案 0 :(得分:1)
如果不加考虑地将所有struct成员声明为可选的,那就是巨大的缺点。
如果该键不存在于结构中,则所有成员均设置为nil
,并且不会引发错误。