如何解决预期的数组,但在 Swift 中找到字典
我是 Swift 中 Codable 的新手,我正在尝试从 API (https://sportspagefeeds.com/documentation) 获取一些数据。我不需要从 API 获取所有数据,只需要在模型中指定字段。尝试运行我的代码时出现此错误:typeMismatch(Swift.Array<Any>,Swift.DecodingError.Context(codingPath: [],debugDescription: "Expected to decode Array<Any> but found a dictionary instead.",underlyingError: nil))
奇怪的是,当我将 API 响应放入字符串中然后对其进行编码时,我可以使用完全相同的代码成功对其进行解码。有人对这里有任何见解吗?我从响应中收到 200
代码
代码:
let request = NSMutableuRLRequest(url: NSURL(string: "https://sportspage-Feeds.p.rapidapi.com/games?league=NBA")! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
session.dataTask(with: request as URLRequest,completionHandler: { (data,response,error) -> Void in
if let data = data {
do {
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let games = try dec.decode([Game].self,from: data)
print(games)
} catch {
print(error)
}
}
}).resume()
API 返回结构(来自链接):
[
{
"gameId":"tv7mnr2-g7c4fe5-p95kxge-ptyhr72","details":{
"league":"NFL","season":2018,"seasonType":"regular","conferenceGame":true,"divisionGame":true
},"schedule":{
"date":"2018-12-30T18:00:00.000Z","tbaTime":false
},"teams":{
"away":{
"team":"Miami Dolphins","location":"Miami","mascot":"Dolphins","abbreviation":"MIA","conference":"AFC","division":"East"
},"home":{
"team":"buffalo Bills","location":"buffalo","mascot":"Bills","abbreviation":"BUF","division":"East"
}
},"venue":{
"name":"New Era Field","city":"Orchard Park","state":"NY","neutralSite":false
},"scoreboard":{
"score":{
"away":17,"home":42,"awayPeriods": [0,14,3,0],"homePeriods": [14,14]
},"currentPeriod":4,"periodTimeRemaining":"0:00"
},[ etc...... ]
]
这是我的模型:
public struct Game: Codable {
public var gameId: String?
public var details: Details?
public var teams: Teams?
public var scoreboard: scoreboard?
}
public struct Details: Codable {
public var league: String?
}
public struct Teams: Codable {
public var home: Team?
public var away: Team?
}
public struct Team: Codable {
public var team: String?
public var abbreviation: String?
}
public struct scoreboard: Codable {
public var score: score?
public var currentPeriod: Int?
public var periodTimeRemaining: String?
}
public struct score: Codable {
public var away: Int?
public var home: Int?
}
解决方法
让我们看看来自 api 的响应:
"status": 200,"time": "2021-03-26T01:42:14.010Z","games": 5,"skip": 0,"results": [....]
响应是字典,但您将其编码为 [Game] 数组,这是您收到此错误的原因。您需要创建更多这样的模型
public struct GameResponse: Codable {
var status: Int
var time: String
var games: Int
var skip: Int
var results: [Game]
}
并将响应解码为 GameResponseModel:
let games = try dec.decode(GameResponse.self,from: data)
把你的游戏id改成Int,因为它不是String
public struct Game: Codable {
public var gameId: Int?
public var details: Details?
public var teams: Teams?
public var scoreboard: Scoreboard?
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。