尝试从Xcode应用程序中的GitHub API获取数据时,没有与Key CodingKeys关联的值 [英] No value associated with key CodingKeys while trying to get data from GitHub API in Xcode app

查看:63
本文介绍了尝试从Xcode应用程序中的GitHub API获取数据时,没有与Key CodingKeys关联的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以请听@Larme和@JoakimDanielson(非常感谢你们!)我开始在URLSession上执行一些任务,以实际从GitHub API获取我要查找的数据。

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

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

使用相关GitHub接口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方法。
第二,使用结构,而不是类。

如果要对存储库进行解码,则必须从根对象开始,存储库位于keyitems的数组中

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也是一个字典,它会变成另一个结构。

若要删除CodingKey,请添加full_name转换为fullName.convertFromSnakeCase策略。

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

这篇关于尝试从Xcode应用程序中的GitHub API获取数据时,没有与Key CodingKeys关联的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆