簡體   English   中英

如何修復CodingKeys的“無關聯值”錯誤?

[英]How to fix the “no value associated” error with CodingKeys?

我正在嘗試從下面的API解碼API,但我仍然收到以下錯誤:

keyNotFound(CodingKeys(stringValue:“resources”,intValue:nil),Swift.DecodingError.Context(codingPath:[_ JSONKey(stringValue:“resources”,intValue:nil)],debugDescription:“沒有與鍵CodingKeys相關的值(stringValue: \\“resources \\”,intValue:nil)(\\“resources \\”)。“,underlyingError:nil))

API地址: https//age-of-empires-2-api.herokuapp.com/docs/

我已經嘗試多次查看我的結構,並在API的不同級別嘗試調用代碼,但仍無法獲取數據。 我也試過用print(resources.XXX)格式調用不同級別的對象。

這是我第一次從API調用數據:

{
  "resources": {
    "civilizations": "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations", 
    "units": "https://age-of-empires-2-api.herokuapp.com/api/v1/units", 
    "structures": "https://age-of-empires-2-api.herokuapp.com/api/v1/structures", 
    "technologies": "https://age-of-empires-2-api.herokuapp.com/api/v1/technologies"
  }
}

這些是結構的前兩個級別:

// MARK: - Resources
struct Resources: Codable {
    let resources: [String : ResourcesList]

    enum CodingKeys: String, CodingKey {
        case resources
    }
}

// MARK: - ResourcesList
struct ResourcesList: Codable {
    let civilizations: CivilizationList
    let units: UnitList
    let structures: StructureList
    let technologies: TechnologyList

    enum CodingKeys: String, CodingKey {
        case civilizations, units, technologies, structures
    }
}

在這些結構下面,我已經實現了API網站中指出的模型,例如CivilizationList,Civilization等。

這是我的通話代碼:

        let jsonUrl = "https://age-of-empires-2-api.herokuapp.com/api/v1"
        guard let url = URL(string: jsonUrl) else { return }
        URLSession.shared.dataTask(with: url) { (data, response, error) in

            guard let data = data else { return }
            let dataAsString = String(data: data, encoding: .utf8)

            do {
                let decoder = JSONDecoder()
                let resources = try decoder.decode([String : Resources].self, from: data)
                print(resources)
            } catch {
                print(error)
            }
            print(dataAsString!)
        }.resume()

我已經回顧了所有其他線程有關相同的錯誤代碼,嘗試過的東西,但可能有一些非常基本的我想念,不幸的是我太初學者注意到了它。 任何幫助表示贊賞。

模型應該是

// MARK: - Empty
struct Resources: Codable {
    let resources: ResourcesList
}

// MARK: - Resources
struct ResourcesList: Codable {
    let civilizations, units, structures, technologies: String
}

解碼

let resources = try decoder.decode(Resources.self, from: data)

civilizations, units, structures, technologies都是字符串而不是模型

要么

let resources = try decoder.decode([String : ResourcesList].self, from: data)

暫無
暫無

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

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