json - Swift JSON 解码字典失败

标签 json swift dictionary decoding jsondecoder

我的结构如下所示:

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) 使用 StringInt 作为您的键类型
c) 使用自定义解码器
d) 使用RawRepresentable-协议(protocol)

关于json - Swift JSON 解码字典失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67087643/

相关文章:

ios - 使用 Swift 2.0 自定义 CalloutView 最佳方法?

ios - 多值设置未使用默认值初始化

swift iOS : Serial Function Execution

python-2.7 - csv.DictReader 是否将文件存储在内存中?

json - CouchDB 通过三个索引键查询和过滤

json - 在 Swift 中将字典转换为 JSON

javascript - 如何最好地将 javascript 解析的 JSON 内容解析为 ruby

json - laravel中以json对象传递数据库数据

c++ - 如何获得二叉树(集合或映射)的根?

python - 使用 type(a) 作为字典键是否合理?