我正在尝试构建一个简单的应用程序,用户可以在其中搜索GitHub存储库,但由于无法正确解码JSON,因此请求失败。我有一个名为“搜索”的模型,如果我使用snake_case表示法命名字段,则解码有效。但是,我想使用camelCase表示法并使用encodingKeys或
    coder.keyDecodingStrategy = .convertFromSnakeCase
但似乎没有一个工作,我想知道为什么

这是我的代码,即请求执行:

open class GetRepositoriesRequest: Request {

    var query: String
    public var headers: [String: String] = [:]
    public var parameters: [String: Any] = [:]
    public var method: RequestMethod = .GET
    public var apiAdress: String

    public init(query: String) {
        self.query = query
        self.apiAdress = "https://api.github.com/search/repositories?q=\(self.query)"
    }

    public func execute() {
        let decoder = JSONDecoder()
        let url = URL(string: self.apiAdress)!
        var request = URLRequest(url: url)
        request.httpMethod = self.method.rawValue
        let dataTask = URLSession.shared.dataTask(with: request) {
            data,response,error in
            do {
                guard let data = data else {
                    return
                }
                if let jsonResult = try? decoder.decode(Search.self, from: data) {
                    print(jsonResult)
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }
        dataTask.resume()
    }
}


和型号:

struct Search: Codable {
    var totalCount: Double
    var incompleteResults: Bool
    var items: [Item]

    public enum SearchKeys: String, CodingKey {
        case totalCount = "total_count"
        case incompleteResults = "incomplete_results"
        case items
    }
}

struct Item: Codable {
    let id: Int
    let node_id:String
    let name: String
    let full_name: String
    let owner: Owner
}

struct Owner: Codable {
    let login: String
    let id: Int
    let node_id:String
}

最佳答案

糟糕,我自己找到了答案。我想我完全忘记了其他模型不是驼峰表示法。对不起

关于json - 为什么不能对 key 或keyDecodingStrategy进行编码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57019726/

10-15 23:10