尝试从 Xcode 应用中的 GitHub API 获取数据时,没有与键 CodingKeys 关联的值

No value associated with key CodingKeys while trying to get data from GitHub API in Xcode app

所以听@Larme 和@JoakimDanielson(非常感谢,伙计们!)我开始在 URLSessions 上做一些任务,以实际从 GitHub API.

这里的最终目标是为存储库创建移动 GitHub 搜索应用程序。

我从本教程中实现了一段代码: https://blog.devgenius.io/how-to-make-http-requests-with-urlsession-in-swift-4dced0287d40

使用相关 GitHub API URL。我的代码如下所示:

import UIKit

class Repository: Codable {
    let id: Int
    let owner, name, full_name: String

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case owner, name, full_name
    }

    init(id: Int, owner: String, name: String, fullName: String) {
        self.id = id
        self.owner = owner
        self.name = name
        self.full_name = full_name
    }
}

(...)

        let session = URLSession.shared
                let url = URL(string: "https://api.github.com/search/repositories?q=CoreData&per_page=20")!
                let task = session.dataTask(with: url, completionHandler: { data, response, error in
                    // Check the response
                    print(response)
                    
                    // Check if an error occured
                    if error != nil {
                        // HERE you can manage the error
                        print(error)
                        return
                    }
                    
                    // Serialize the data into an object
                    do {
                        let json = try JSONDecoder().decode(Repository.self, from: data! )
                            //try JSONSerialization.jsonObject(with: data!, options: [])
                        print(json)
                    } catch {
                        print("Error during JSON serialization: \(error.localizedDescription)")
                        print(String(describing:error))
                    }
                    
                })
                task.resume()
        
        
    }
    


} 

完整的错误文本是:

keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))

我尝试删除一些有此错误的值,但其他值仍然抛出相同的错误,我使用了可以在 GitHub 文档中找到的编码键: https://docs.github.com/en/rest/reference/search#search-repositories

请帮忙!

首先你不需要CodingKeysinit方法。
其次使用结构,而不是 类.

如果要解码必须从根对象开始的存储库,存储库位于键 items

的数组中
struct Root : Decodable {
    let items : [Repository]
}

struct Repository: Decodable {
    let id: Int
    let name, fullName: String
    let owner : Owner
}

struct Owner : Decodable {
    let login : String
}

另一个问题是 owner 也是一个字典,它变成了另一个结构。

要摆脱 CodingKeys 添加 .convertFromSnakeCase 策略,该策略 full_name 转换为 fullName

let session = URLSession.shared
let url = URL(string: "https://api.github.com/search/repositories?q=CoreData&per_page=20")!
let task = session.dataTask(with: url) { data, response, error in
    // Check the response
    print(response)
    // Check if an error occured
    if let error = error {
        // HERE you can manage the error
        print(error)
        return
    }
    
    // Serialize the data into an object
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let json = try decoder.decode(Root.self, from: data! )
        print(json)
    } catch {
        print("Error during JSON serialization:", error)
    }
}
task.resume()