Swift词典API";没有与键CodingKeys(字符串值:"type",intVal



我遇到一个错误,显示";类型";从API中获取。我试着浏览了其他围绕这一点的帖子,但找不到任何对我有用的东西,而不引起另一个问题。

我得到的全部错误是";没有与键CodingKeys(字符串值:"type",intValue:nil(("type"(关联的值&";,underlyingError:nil((

我试图从中获取的API是:https://github.com/ToontownRewritten/api-doc/blob/master/invasions.md

import UIKit
struct InvasionList: Decodable {
let type: String
let asOf: Int?
let progress: String?


}
class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
let jsonUrlString = "https://www.toontownrewritten.com/api/invasions"
guard let url = URL(string: jsonUrlString) else { return }

URLSession.shared.dataTask(with: url) { (data, response, err) in

guard let data = data else {return }

do {
let invasions = try JSONDecoder().decode(InvasionList.self, from: data)
print(invasions.type)


} catch let err {
print(err)
}


}.resume()

}

}

您的InvasionList实际上与您试图解码的JSON的结构不匹配。它只匹配其中的一小部分,但你需要解码整个东西。这包括最外面的包装器(具有lastUpdated的部分和每个"入侵"的动态密钥(。

下面是一个工作示例:

let jsonData = """
{"lastUpdated":1624230138,"invasions":{"Gulp Gulch":{"asOf":1624230127,"type":"Robber Baron","progress":"3797/7340"},"Splashport":{"asOf":1624230129,"type":"Ambulance Chaser","progress":"2551/8000"},"Kaboom Cliffs":{"asOf":1624230131,"type":"Money Bags","progress":"5504/6000"},"Boingbury":{"asOf":1624230132,"type":"Tightwad","progress":"4741/8580"}},"error":null}
""".data(using: .utf8)!
struct InvasionWrapper: Decodable {
let lastUpdated : Int
let invasions : [String:Invasion]
}
struct Invasion: Decodable {
let type: String
let asOf: Int?
let progress: String?
}
do {
let list = try JSONDecoder().decode(InvasionWrapper.self, from: jsonData)
print(list)
} catch {
print(error)
}

相关内容

  • 没有找到相关文章

最新更新