我正在使用F1 API,并希望在一个快速项目中显示所有驱动程序名称。我正在使用可编码协议,并且我了解如何从JSON API访问一个名称或属性。只是我想从该JSON API访问所有选定的属性。我尝试了无数种不同的方法来实现这一目标,但收效甚微。下面是我的代码。
struct MRData: Codable {
let xmlns: String
let series: String
let url: String
let limit, offset, total: String
let standingsTable: StandingsTable
enum CodingKeys: String, CodingKey {
case xmlns, series, url, limit, offset, total
case standingsTable = "StandingsTable"
}
}
struct StandingsTable: Codable {
let season: String
let standingsLists: [StandingsList]
enum CodingKeys: String, CodingKey {
case season
case standingsLists = "StandingsLists"
}
}
struct StandingsList: Codable {
let season, round: String
let driverStandings: [DriverStanding]
enum CodingKeys: String, CodingKey {
case season, round
case driverStandings = "DriverStandings"
}
}
struct DriverStanding: Codable {
let position, positionText, points, wins: String
let driver: Driver
let constructors: [Constructor]
enum CodingKeys: String, CodingKey {
case position, positionText, points, wins
case driver = "Driver"
case constructors = "Constructors"
}
}
struct Constructor: Codable {
let constructorId: String
let url: String
let name: String
let nationality: String
}
struct Driver: Codable {
let driverId: String
let url: String
let givenName, familyName, dateOfBirth, nationality: String
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let jsonUrlString = "https://ergast.com/api/f1/1981/driverstandings.json"
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 f1Data = try JSONDecoder().decode(F1Data.self, from: data)
let season = f1Data.mrData.standingsTable.season
print(f1Data.mrData.standingsTable.standingsLists[0].
driverStandings[1].driver.familyName)
print(season)
} catch {
print(error)
}
}.resume()
}
任何帮助将不胜感激。
答案 0 :(得分:0)
添加一个for循环。
UpperCaseField