gpt4 book ai didi

ios - 无法从 JSONDecoder 获取数据,没错,我编的结构?

转载 作者:行者123 更新时间:2023-11-28 05:41:52 27 4
gpt4 key购买 nike

我有这样一个结构,我拿了一 block 来获取数据。这是我的代码。为什么我不能从 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,

}]

我的代码结构尝试了 decode 和 "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?


}

我的加载url 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()

}
}

最佳答案

你需要

let player = try decoder.decode([PlayerRoster].self, from: data)

你的 json 的根是一个由 [] 指示的数组,这样做有助于了解问题

} catch {
print("Failed to decode : \(error)")
}

加上

let id: Int?
let apiId:Int?

关于ios - 无法从 JSONDecoder 获取数据,没错,我编的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56365394/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com