Swift Codable:使用未知键解码字典 [英] Swift Codable: decode dictionary with unknown keys

查看:253
本文介绍了Swift Codable:使用未知键解码字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Codable 非常有用。但是,如果您不知道按键怎么办?我目前正面临这个问题。

Codable is great when you know the key formatting of the JSON data. But what if you don't know the keys? I'm currently faced with this problem.

通常我希望返回JSON数据,如下所示:

Normally I would expect JSON data to be returned like this:

{
"id": "<123>",
"data": [
    {
        "id": "<id1>",
        "event": "<event_type>",
        "date": "<date>"
    },
    {
        "id": "<id2>",
        "event": "<event_type>",
        "date": "<date>"
    },
]
}

但这就是我'm旨在解码:

But this is what I'm aiming to decode:

{
"id": "123",
"data": [
    { "<id1>": { "<event>": "<date>" } },
    { "<id2>": { "<event>": "<date>" } },
]
}

问题是:如何使用 Codable 解码键唯一的JSON?我觉得我缺少明显的东西。

Question is: how do I use Codable to decode JSON where the keys are unique? I feel like I'm missing something obvious.

这就是我希望这样做的原因,因此我可以使用 Codable

This is what I'm hoping to do so I can use Codable:

struct SampleModel: Codable {
    let id: String
    let data: [[String: [String: Any]]]

    // MARK: - Decoding

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case data = "data"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        id = try container.decode(String.self, forKey: .id)
        // This throws an error: Ambiguous reference to member 'decode(_:forKey:)'
        data = try container.decode([[String: [String: Any]]].self, forKey: .data)
    }
}

这将引发错误:对成员'decode(_:forKey:)'

推荐答案

用于完全更改的任务离子,溶液非常相似。您的结构只是在数组上方添加了一层。不需要任何自定义解码,甚至不需要任何CodingKeys。

For your completely changed question, the solution is very similar. Your struct simply adds one additional layer above the array. There's no need for any custom decoding nor even any CodingKeys.

请注意,您不能在任意位置使用任何

Note that you can't use Any in a Codable.

let json="""
{
"id": "123",
"data": [
    { "<id1>": { "<event>": "2019-05-21T16:15:34-0400" } },
    { "<id2>": { "<event>": "2019-07-01T12:15:34-0400" } },
]
}
"""
struct SampleModel: Codable {
    let id: String
    let data: [[String: [String: Date]]]
}

var decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
    let res = try decoder.decode(SampleModel.self, from: json.data(using: .utf8)!)
    print(res)
} catch {
    print(error)
}






原始问题的原始答案。


The original answer for your original question.

由于您有一个嵌套的字典数组,其中没有一个字典键是固定的,并且由于没有其他字段,因此您可以将其解码为纯数组。

Since you have an array of nested dictionary where none of the dictionary keys are fixed, and since there are no other fields, you can just decode this as a plain array.

以下是示例:

let json="""
[
    { "<id1>": { "<event>": "2019-07-01T12:15:34-0400" } },
    { "<id2>": { "<event>": "2019-05-21T17:15:34-0400" } },
]
"""
var decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
    let res = try decoder.decode([[String: [String: Date]]].self, from: json.data(using: .utf8)!)
    print(res)
} catch {
    print(error)
}

这篇关于Swift Codable:使用未知键解码字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆