I'm failing to correctly parse this JSON, I get the following error:
"keyNotFound(CodingKeys(stringValue: "GameEntries", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"GameEntries\", intValue: nil) (\"GameEntries\").", underlyingError: nil))"
I think my issue is probably due with parsing a dictionary vs an array, but I'm starting to get lost.
JSON:
{
fullgameschedule = {
gameentry = (
{
awayTeam = {
Abbreviation = SEA;
City = Seattle;
ID = 123;
Name = Mariners;
};
date = "2019-03-20";
homeTeam = {
Abbreviation = OAK;
City = Oakland;
ID = 125;
Name = Athletics;
};
id = 48847;
location = "Tokyo Dome";
time = "5:35AM";
},
{
awayTeam = {
Abbreviation = CHC;
City = Chicago;
ID = 131;
Name = Cubs;
};
date = "2019-09-29";
homeTeam = {
Abbreviation = STL;
City = "St. Louis";
ID = 133;
Name = Cardinals;
};
id = 48879;
location = "Busch Stadium";
time = "3:15PM";
}
);
lastUpdatedOn = "2019-04-27 9:38:51 AM";
};
}
My structs:
struct FullGameSchedule: Decodable
{
let GameEntries: GameEntries
let lastUpdatedOn: String
}
struct GameEntries: Decodable
{
let Games = [Game]()
}
struct Game: Decodable
{
let awayTeam: Team
let date: String
let homeTeam: Team
let id: Int
let location: String
let time: String
}
struct Team: Decodable
{
let Abbreviation: String
let City :String
let ID: Int
let Name:String
}
My parsing:
guard let url = URL(string: "blah") else { return }
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
guard let data = data else {return }
do {
let games = try JSONDecoder().decode(FullGameSchedule.self, from: data)
print(games)
//let json = try JSONSerialization.jsonObject(with: data, options: [])
//print(json)
} catch {
print(error)
}
}.resume()
My hope is that I can get the JSON into the games objet so that I can then filter down and pull specific details about arbitrary games throughout the season based on user input.
Your property names and first two structs don't match your JSON. You need:
You may also wish to make use of specifying CodingKeys so you can properly name your struct properties with appropriate camelCase.