我有这样的结构,我花了一点时间来获取数据。这是我的代码,为什么我不能从Api获取数据?任何人都可以帮忙和举例说明答案,似乎都正确。我将非常感谢。
[{
"id": 142636,
"apiId": 353056,
"shortName": "K. McKenzie-Lyle",
"firstName": "Kai",
"middleName": null,
"lastName": "McKenzie-Lyle",
"imageFileName": null,
"height": 195,
"weight": 86,
"birthDate": "1997-11-30T00:00:00",
"contractExpiration": null,
"onLoanSquadTillDate": null,
"oldApiId": 344534,
"age": 22,
"birthAreaId": 80,
"passportAreaId": 110,
"footName": "Right",
"male": true,
"currentSquadId": 20401,
"parentSquadId": 46,
"nationalSquadId": 31885,
}]
我的代码结构尝试解码和“ id”等。
struct PlayerRoster:Codable {
let id: String?
let apiId:String?
let shortName: String?
let firstName: String?
let middleName:String?
let lastName:String?
let imageFileName:String?
let height:Double?
let weight:Double?
}
我的加载网址api地址。
func loadingApi(){
let urlData = "https://apidev.transferroom.com/api/values"
guard let url = URL(string: urlData) else { return }
let task = URLSession.shared.dataTask(with: url) { (data,response,error) in
guard let data = data else { return }
guard error == nil else {return}
do {
let decoder = JSONDecoder()
//using the array to put values
let player = try decoder.decode(PlayerRoster.self, from: data)
self.updatedPlauers = player
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
task.resume()
}
}
答案 0 :(得分:1)
您需要
let player = try decoder.decode([PlayerRoster].self, from: data)
您的json的根是由[]
表示的数组,这样做可以帮助您了解问题所在
} catch {
print("Failed to decode : \(error)")
}
加
let id: Int?
let apiId:Int?