【发布时间】:2021-07-09 06:16:27
【问题描述】:
我的结构如下图:
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/String 相关。所以我也做了下面的测试,从来没有失败过。
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 时它会起作用,因为它显然可以正确解码?
【问题讨论】:
-
这似乎是一个unresolved bug,也有人可能会争论使用外部创建的 uuid 值的价值。它们是否保证在您的设备中是唯一的,我不确定
-
在我看来这不是一个错误。字典中的键是
Decodable的事实并没有太大区别,因为 JSON 仅支持String作为字典键。但是,Decodable不能强制密钥类型可以解码String。因此他们有一个选择 - 尝试将String解码为给定类型,如果不可能,则抛出异常,或者在找到非字符串键时使用不同的方式存储数据。第一种可能在编码时会出现问题,所以他们选择了第二种。
标签: json swift dictionary decoding jsondecoder