Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))
`import Foundation
struct Game: Codable, Identifiable{
var id = UUID()
var title: String
var normalPrice: String
var sellPrice: String
var steamRatingPercent: String
var thumb: String
}
// means data will be read faster in much easier fashion
class API: ObservableObject{
// for updating status of the variable [everytime it updates ]
@Published var games = [Game]()
func loadData(url: String, completion: @escaping ([Game]) -> ()){
guard let url = URL(string: url)
else{
print("Invalid data")
return
}
// decoding JSON data into [Game] array
URLSession.shared.dataTask(with: url){data, response, error in
let games = try! JSONDecoder().decode([Game].self, from: data!)
print(games)
DispatchQueue.main.async{
completion(games)
}
}.resume()
}
}
Check that the JSON contains what the Codable
struct Game
and the decoders/encoders expect.
This works for me nicely:
import Foundation
struct Game: Codable, Identifiable{
var id = UUID()
var title: String
var normalPrice: String
var sellPrice: String
var steamRatingPercent: String
var thumb: String
}
let game = Game(id: UUID(), title: "Test", normalPrice: "12.12", sellPrice: "10.00", steamRatingPercent: "10", thumb: "Yeah")
let gameEncoded = try JSONEncoder().encode(game);
if let encodedAsString = String(data: gameEncoded, encoding: .utf8) {
print("\(encodedAsString)")
}
let json =
"""
{"id":"CCA746E3-CC22-44F4-AF51-9C012B8D9B52", "sellPrice":"100.00", "title":"Test 2", "thumb":"Yeah 2", "normalPrice":"112.00", "steamRatingPercent":"15"}
"""
let data = json.data(using: .utf8)
let game2 = try JSONDecoder().decode(Game.self, from: data!)
print("\(game2)")
Printing out:
{"sellPrice":"10.00","id":"CD7DD9E6-B314-4DCF-9F3C-43ED2C7B50DD","title":"Test","thumb":"Yeah","normalPrice":"12.12","steamRatingPercent":"10"}
Game(id: CCA746E3-CC22-44F4-AF51-9C012B8D9B52, title: "Test 2", normalPrice: "112.00", sellPrice: "100.00", steamRatingPercent: "15", thumb: "Yeah 2")