我正在尝试使用 Structs 解码 nfl 播放器的 json 文件,但在检查第一个播放器的 PlayerID 后它一直失败,该播放器从不为空。我不确定我做错了什么,但我真的很感谢你的指导,我想我已经盯着这个看了整整 24 小时。
这是我的结构:
// MARK: PLAYERS.JSON STRUCTS
struct playersArrayJSON: Codable {
let lastUpdatedOn: String
let players: Array<nflPlayers>
enum CodingKeys: String, CodingKey {
case lastUpdatedOn = "lastUpdatedOn"
case players = "players"
}
}
struct nflPlayers: Codable {
let playerID: Int
let first: String
let last: String
let POS: String?
let team: nflTeam?
let imageSrc: String?
let currentInjury: injury?
enum CodingKeys: String, CodingKey {
case playerID = "id"
case first = "firstName"
case last = "lastName"
case POS = "primaryPosition"
case team = "currentTeam"
case imageSrc = "officialImageSrc"
case currentInjury = "currentInjury"
}
}
struct nflTeam: Codable {
let teamID: Int
let abbv: String
enum CodingKeys: String, CodingKey {
case teamID = "id"
case abbv = "abbreviation"
}
}
struct injury: Codable {
let description: String
let designation: String
enum CodingKeys: String, CodingKey {
case description = "description"
case designation = "playingProbability"
}
}
这是我调用来解码 Json 的函数:
func decodePlayersJSON() {
// Get the players.json from docdir
if let documentDirectory = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first {
let pathWithFileName = documentDirectory.appendingPathComponent("players.json")
let fileUrl = URL(fileURLWithPath: pathWithFileName.path)
do { // See if the players.json exist in docdir
let data = try Data(contentsOf: fileUrl, options: .mappedIfSafe)
// Exists in DocDir - Try decoding JSON and writing to jsonLocalArray
if let searchResult: playersArrayJSON = try! JSONDecoder().decode(playersArrayJSON.self, from:data) {
jsonLocalArray = searchResult
print("Players.Json decoded successfully")
DispatchQueue.main.async {
self.lblDetails.text = "player's database updated successfully"
self.performSegue(withIdentifier: "toQuiz", sender: nil)
}
print(jsonLocalArray)
} else {
print("Error decoding players.json.")
}
} catch {
print("No data found when decoding players.json")
}
}
}
这是我在控制台中遇到的错误:
致命错误:“试试!” 表达式意外引发错误:Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "players", intValue: nil), _JSONKey(stringValue : "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil)): 文件 CoachesChallenge/UpdatingVC .swift,第 293 行 2020-10-09 18:08:08.412910-0700 CoachesChallenge[32143:2136162] 致命错误:“尝试!” 表达式意外引发错误:Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "players", intValue: nil),
***非常感谢任何帮助和反馈!!!!先感谢您!!!