成功的第一反應:
{
"url": "demo.web.link",
"id": "345345dgfgdfg34534545",
"firstName": "Apple",
"lastName": "iOS",
"email": "[email protected]",
"phone": ""
}
當發布資料不正確時得到此回應:
{
"message": "The given data was invalid.",
"errors": {
"code": [
"The provided code does not exist."
]
}
}
我正在使用這個結構:
struct AuthenticateResponse: Decodable {
let url, id, firstName, lastName: String?
let email, message, phone: String?
let errors: Errors?
}
// MARK: - Errors
struct Errors: Decodable {
let code: [String]?
}
我的結構為成功而作業,但不為失敗而作業。我想知道我做錯了什么。
當我提供不正確的資料時出現此錯誤:
Error#####: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))
成功回應:
"RESPONSE JSON"
username Response: AuthenticateResponse(url: nil, id: nil, firstName: nil, lastName: nil, email: nil, message: nil, phone: nil, status: Optional("available"), errors: nil)
uj5u.com熱心網友回復:
發布的代碼在傳遞給 a 時確實正確決議了 json,JSONDecoder因此可能存在與它所使用的背景關系有關的內容,這可能會導致問題。
但是,當前模型要求所有欄位都是可選的。這在應用程式的其他部分可能很煩人,它需要檢查每個值是否存在才能在 UI 中顯示。
可以將其更改為兩種不同的型別,以消除對可選欄位的需要。然后可以將其包裝為回應型別中的兩種情況,它們嘗試將其解碼為成功,而失敗則嘗試將其決議為失敗并回傳值。
enum AuthenticateResponse: Decodable {
struct Success: Decodable {
let url, id, firstName, lastName: String
let email, phone: String
}
struct Failure: Decodable {
struct Errors: Decodable {
let code: [String]
}
let message: String
let errors: Errors
}
case success(Success)
case failure(Failure)
init(from decoder: Decoder) throws {
do {
let success = try Success(from: decoder)
self = .success(success)
} catch {
let failure = try Failure(from: decoder)
self = .failure(failure)
}
}
}
uj5u.com熱心網友回復:
當您插入不正確的資料時它正在作業,需要強制設定您的標題
request.setValue("application/json", forHTTPHeaderField: "Accept")
在我使用之前:
if path.httpMethod == .get {
request.setValue("application/json", forHTTPHeaderField: "Accept")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/415111.html
標籤:
