我正在尝试解析url中的数据,但是我无法将对象添加到我的游戏数组中,我陷入了调试印记(“无法解析数据”)。我的类Game继承自Codable,所以我看不出我遗漏了什么。
var games = [Game]()
func download(at url: String, handler: @escaping (Data?) -> Void)
{
// 1 - Create URL
guard let url = URL(string: url) else {
debugPrint("Failed to create URL")
handler(nil)
return
}
// 2 - Create GET Request
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "GET"
// 3 - Create download task, handler will be called when request ended
let task = URLSession.shared.dataTask(with: request) {
(data, response, error) in handler(data)
}
task.resume()
}
func getGames() {
// 1 - Download games
download(at: "https://education.3ie.fr/ios/StarterKit/GameCritic/GameCritics.json")
{ (gameData) in
if let gameData = gameData {
// 2 - Decode JSON into a array of Game object
let decoder: JSONDecoder = JSONDecoder()
do {
self.games = try decoder.decode([Game].self, from: gameData)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
debugPrint("Failed to parse data") // I fail here
}
}
else
{
debugPrint("Failed to parse data - error: \(error)")
}
}
}
override func viewDidLoad() {
getGames()
for elm in games
{
debugPrint(elm)
}
super.viewDidLoad()
}
输出:
"Failed to parse data - error: keyNotFound(CodingKeys(stringValue: \"small_path\", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: \"Index 0\", intValue: 0)], debugDescription: \"No value associated with key CodingKeys(stringValue: \\\"small_path\\\", intValue: nil) (\\\"small_path\\\").\", underlyingError: nil))"
发布于 2020-06-07 09:31:08
看起来您就快成功了:)
你说
我用smallImageUrl替换了small_path
但是请看一下来自https://education.3ie.fr/ios/StarterKit/GameCritic/GameCritics.json的JSON
这里有一条:
{
"id" : 0,
"name" : "Shenmue",
"smallImageURL" : "https://education.3ie.fr/ios/StarterKit/GameCritic/small0.jpg",
"bigImageURL": "https://education.3ie.fr/ios/StarterKit/GameCritic/big0.jpg",
"score": 16,
"platform": "dreamcast"
},
正确的名称是smallImageURL
,但在您的Swift Game
结构/类中,您有一个名为smallImageUrl
的属性(与JSON中的大写"rl“相比,Url中的"RL”是小写的)。这足以让JSONDecoder
放弃所有的希望,真正地给up...yes!:)
因此,首先,尝试将您的属性从
smallImageUrl
至
smallImageURL
看看这会把你带到什么地方。
为属性选择不同的名称
如果你想为你的Swift变量使用一个不同于你收到的JSON中引用的名称,例如smallImageUrl
而不是smallImageURL
。我鼓励您查看用于编码/解码的documentation,更具体的部分名为:“选择属性以使用编码键进行编码和解码”
祝好运。
https://stackoverflow.com/questions/62217347
复制相似问题