找不到密钥,正在努力解析Swift 4中的嵌套JSON

找不到密钥,正在努力解析Swift 4中的嵌套JSON,json,swift,parsing,Json,Swift,Parsing,我无法正确解析此JSON,出现以下错误: “keyNotFound(编码键(stringValue:“GameEntries”,intValue:nil),Swift.DecodingError.Context(编码路径:[],调试说明:“没有与键编码键关联的值(stringValue:\“GameEntries\”,intValue:nil)(“GameEntries\”),UnderingError:nil”)” 我想我的问题可能是由于解析字典而不是数组,但我开始迷路了 JSON: 我的结构

我无法正确解析此JSON,出现以下错误:

“keyNotFound(编码键(stringValue:“GameEntries”,intValue:nil),Swift.DecodingError.Context(编码路径:[],调试说明:“没有与键编码键关联的值(stringValue:\“GameEntries\”,intValue:nil)(“GameEntries\”),UnderingError:nil”)”

我想我的问题可能是由于解析字典而不是数组,但我开始迷路了

JSON:

我的结构:

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
}
我的解析:

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()

我希望我可以将JSON输入到games对象中,这样我就可以根据用户输入过滤并提取整个赛季任意游戏的具体细节。

您的属性名称和前两个结构与您的JSON不匹配。你需要:

struct FullGameSchedule: Decodable
{
    let fullgameschedule: GameEntries
}

struct GameEntries: Decodable
{
    let gameentry: [Game]
    let lastUpdatedOn: String
}

您可能还希望使用指定编码键,以便使用适当的camelCase正确命名结构属性。

就是这样!非常感谢。我会去研究编码键当这起作用时,GameEntries是一个空数组,有什么想法吗?你是说
gameentry
是一个空数组吗?编辑你的问题并发布实际的JSON,而不是打印字典的输出。请参阅我的更新答案。
gameentry
行有一个输入错误。
struct FullGameSchedule: Decodable
{
    let fullgameschedule: GameEntries
}

struct GameEntries: Decodable
{
    let gameentry: [Game]
    let lastUpdatedOn: String
}