【问题标题】:Decode Dictionary with Random Initial Key使用随机初始密钥解码字典
【发布时间】:2019-09-28 18:13:39
【问题描述】:

我正在接收并尝试解析包含事件数据的 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))

我在这里缺少什么?我觉得这应该比较简单,我一定是完全忽略了一些东西。

【问题讨论】:

标签: swift jsondecoder


【解决方案1】:

你需要

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
}

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

【讨论】:

  • 澄清点:在 JSON 中,{} 表示字典,[] 表示数组。
  • 使用此方法后如何获取事件本身?当我现在打印 eventData 时,它给了我一个"RandomKey": Package.Event(eventTitle: "blah blah", description: "blah blah", timeStart: "blah blah", timeEnd: "blah blah") 的数组。但我需要能够将每个事件传递给单元格视图
  • 具体来说,尝试设置self.events = eventData 失败说它Cannot assign value of type '[String:Event]' to type '[Event]?'
  • self.events = Array(eventData.values)
猜你喜欢
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
相关资源
最近更新 更多