我的结构如下所示:
struct ItemList: Decodable {
var items: [UUID: Int]
}
我得到的示例 JSON 数据是:
{
"items": {
"b4f8d2fa-941f-4f9a-a98c-060bbd468575": 418226428193,
"81efa661-4845-491b-8bf4-06d5dff1d5f8": 417639857722
}
}
现在,当我尝试解码上述数据时,我收到一个有趣的错误。显然,我没有解码数组,并且显然所有内容都指向字典。
try JSONDecoder().decode(ItemList.self, from: data)
// typeMismatch(
// Swift.Array<Any>,
// Swift.DecodingError.Context(
// codingPath: [
// CodingKeys(stringValue: "items", intValue: nil)
// ],
// debugDescription: "Expected to decode Array<Any> but found a dictionary instead.",
// underlyingError: nil
// )
// )
所以我去尝试并将 [UUID: Int]
更改为 [String: Int]
,这确实使这项工作有效,几乎让我认为错误不是数组/字典相关,但UUID/字符串相关。所以我也做了如下测试,从来没有失败过。
let list = try JSONDecoder().decode(ItemList.self, from: data)
for (key, value) in list.items {
// This will never print `nil`
print(UUID(uuidString: key))
}
所以我的问题是,为什么在解码时会出现这个奇怪的 typeMismatch
错误,以及为什么当我将 UUID
更改为 String< 时它会起作用
,因为它可以清楚地正确解码?
最佳答案
this文章很好地解释了为什么会发生这种情况以及您可以采取哪些措施。简短摘要:
- Swift 将字典编码为数组,其中每个值都跟随一个键
- 您可以使用多种方法来解决该问题:
a) 使用字典的数组表示转向 swift 的方式
b) 使用 String
或 Int
作为您的键类型
c) 使用自定义解码器
d) 使用RawRepresentable
-协议(protocol)
关于json - Swift JSON 解码字典失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67087643/