【问题标题】:Swift JSON decoding dictionary failsSwift JSON解码字典失败
【发布时间】: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


【解决方案1】:

this 文章很好地解释了为什么会发生这种情况以及您可以做些什么。简短总结:

  • Swift 将字典编码为数组,其中每个值都跟随一个键
  • 您可以使用以下几种方法来解决此问题:

a) 使用 dict 的数组表示以 swift 的方式使用
b) 使用String 或Int 作为您的密钥类型
c) 使用自定义解码器
d) 使用RawRepresentable-协议

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    相关资源
    最近更新 更多