簡體   English   中英

Swift 錯誤:keyNotFound 沒有與鍵 CodingKeys 關聯的值

[英]Swift Error: keyNotFound No value associated with key CodingKeys

嘗試解析 JSON 響應並遇到此錯誤。

keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id" )。”,基礎錯誤:無))

因為響應包含一個 id,所以我並沒有對為什么它首先為 id 尋找 CodingKey 做出正面或反面。

這是來自服務器的 JSON 響應:

{
    "answer": {
        "id": 6,
        "title": "Here is the postman API answer",
        "ownerId": 1
    }
}

這是我試圖將其合並到的結構:

// MARK: - Answer
struct Answer: Codable {
    let id: Int
    let title: String
    let ownerID: Int
    let questionID, projectID: Int?

    enum CodingKeys: String, CodingKey {
        case id, title
        case ownerID = "ownerId"
        case questionID = "questionId"
        case projectID = "projectId"
    }
}

這是 function:

func createAnswer(questionId: Int, title: String, completed: @escaping(Result<Answer, AuthenticationError>) -> Void){
guard let url = URL(string: "https://mywebsitehere.com/api") else {
    completed(.failure(.custom(errorMessage:"URL unavailable")))
    return
}

guard let Accesstoken = UserDefaults.standard.string(forKey: "access-token") else { return }
guard let client = UserDefaults.standard.string(forKey: "client") else { return }
guard let uid = UserDefaults.standard.string(forKey: "userEmail") else { return }

let body = AnswerCreateBody(title: title)

var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue(Accesstoken, forHTTPHeaderField: "access-token")
        request.addValue(client, forHTTPHeaderField: "client")
        request.addValue(uid, forHTTPHeaderField: "uid")
        request.addValue("Bearer", forHTTPHeaderField: "Tokentype")
        request.addValue("keep-alive", forHTTPHeaderField: "Connection")
        request.httpBody = try? JSONEncoder().encode(body)

URLSession.shared.dataTask(with: request) { (data, response, error) in
    
    if let response = response as? HTTPURLResponse {
        
        let statusCode = response.statusCode
        
        if (statusCode != 200){
            print(statusCode)
            completed(.failure(.custom(errorMessage: "Authentication Failed.  Need to login again")))
        }

        guard let data = data, error == nil else { return }
        do {
         let answerCreateResponse = try JSONDecoder().decode(Answer.self, from: data)
         completed(.success(answerCreateResponse))
            print(answerCreateResponse)
        } catch {
            print(error)
        }
    }
}.resume()
}

為什么我會收到此錯誤,我該如何糾正?

這是一個常見的錯誤。 您忽略了根 object,帶有關鍵answer的字典當然沒有關鍵id

添加這個結構

struct Root: Decodable {
    let answer : Answer
}

並解碼

let answerCreateResponse = try JSONDecoder().decode(Root.self, from: data).answer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM