我正在接收并尝试解析包含事件数据的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))
我在这里想念什么?我觉得这应该相对简单,我必须完全忽略一些东西。
答案 0 :(得分: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
}
{}
表示字典,[]
表示数组