Swift Error: keyNotFound No value associated with key 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").", underlyingError: nil))

由于响应包含一个 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"
    }
}

这是函数:

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()
}

为什么会出现此错误以及如何更正它?

这是一个常见的错误。您忽略了根对象,带有键 answer 的字典当然没有键 id

添加这个结构

struct Root: Decodable {
    let answer : Answer
}

并解码

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