用随机初始密钥解码字典

Decode Dictionary with Random Initial Key

我正在接收并尝试解析包含事件数据的 json 文件。它是一个像这样组织的字典的字典,其中有一个随机事件 ID # 作为每个字典的键:

{
    "19374176-122" : 
    {
        "event_title" : "Cool Fun Thing to Do",
        "description" : "Have fun and do something cool",
        "time_start" : "13:00:00",
        "time_end" : "14:00:00"
    },
    "9048-5761634" :
    {
        "event_title" : "Nap Time",
        "description" : "Lay down and go to sleep.",
        "time_start" : "15:00:00",
        "time_end" : "16:00:00"
    }
}

我已经为活动创建了结构

struct Event: Codable{
    let event_title: String
    let description: String
    let time_start: String
    let time_end: String
}

并尝试解码

do{
    let eventData = try JSONDecoder().decode([Event].self, from: data)    
        DispatchQueue.main.async {
            print(eventData)
            //self.events = eventData
            self.collectionView?.reloadData()
        }
    } catch let jsonError{
        print(jsonError)
}

但是我得到了一个错误,我试图解码一个数组但是得到了一个字典

typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

然后我尝试为 json 文件的根目录创建一个结构

struct Root: Codable {
    let event_number: Event
}

然后解码

do{
    let eventData = try JSONDecoder().decode(Root.Event.self, from: data)    
        DispatchQueue.main.async {
            print(eventData)
            //self.events = eventData
            self.collectionView?.reloadData()
        }
    } catch let jsonError{
        print(jsonError)
}

但是因为这个字典的键实际上不是 "event_number" 我无法得到那个数据

keyNotFound(CodingKeys(stringValue: "event_number", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"event_number\", intValue: nil) (\"event_number\").", underlyingError: nil))

我在这里错过了什么?我觉得这个应该比较简单,我肯定是完全忽略了什么。

你需要

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let eventData = try decoder.decode([String:Event].self, from: data)   

struct Event: Codable {
   let eventTitle, description, timeStart, timeEnd: String
}

{}表示字典,[]表示数组