我必须解码字典的数组,其中键是枚举,值是模型对象。
这是我的示例JSON
[
{
"nanomp4": {
"url": "https://media.tenor.com/videos/a1da4dcf693c2187615721d866decf00/mp4",
"dims": [
150,
138
],
"duration": 2.0,
"preview": "https://media.tenor.com/images/17d523e6b7c3c9a4ca64566a1890d94d/tenor.png",
"size": 70381
},
"nanowebm": {
"url": "https://media.tenor.com/videos/aa983425114e32ab446f669d91611938/webm",
"dims": [
150,
138
],
"preview": "https://media.tenor.com/images/17d523e6b7c3c9a4ca64566a1890d94d/tenor.png",
"size": 53888
},
},
{
"nanomp4": {
"url": "https://media.tenor.com/videos/a1da4dcf693c2187615721d866decf00/mp4",
"dims": [
150,
138
],
"duration": 2.0,
"preview": "https://media.tenor.com/images/17d523e6b7c3c9a4ca64566a1890d94d/tenor.png",
"size": 70381
},
}
]
这是我的解码代码,
do {
let data = try Data(contentsOf: fileURL)
let decoder = JSONDecoder()
let collection = try decoder.decode([[GIFFormat:Media]].self, from: data)
print(collection)
} catch {
print("Error in parsing/decoding JSON: \(error)")
}
这里GIFFormat
是枚举,Media
是模型对象,它们解码得很好。
enum GIFFormat: String, Decodable {
case nanoMP4 = "nanomp4"
case nanoWebM = "nanowebm"
}
struct Media: Decodable {
let url: URL?
let dims: [Int]?
let duration: Double?
let preview: URL?
let size: Int64?
}
我的控制台打印,
typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
有人可以告诉我这里到底有什么问题吗?
答案 0 :(得分:2)
即使rawValue
的{{1}}是GIFFormat
,String
本身也是一个枚举。您应该更新
GIFFormat
到
let collection = try decoder.decode([[GIFFormat:Media]].self, from: data)
更新:针对您的评论
现在要获取价值,我需要这样使用,
let collection = try decoder.decode([[GIFFormat.RawValue:Media]].self, from: data)
。哪个又丑 !!
我建议您进行一些重构。您可以从完全删除collection?.first?[GIFFormat.mp4.rawValue]?.url
开始。保留您的enum
结构。创建一个新的Media
结构
Collection
然后,您可以将上面的行更新为
struct Collection: Decodable {
let nanomp4: Media!
let nanowebm: Media!
}
和您的丑陋行变成
let collection = try decoder.decode([Collection].self, from: data)
注意::此解决方案假定您仅将collection.first?.nanomp4.url
和nanomp4
作为枚举值。如果不是这种情况,那么这可能不是最佳解决方案,您可能不得不采用第一个解决方案。