首页 > 解决方案 > Swift 4.2 Decoding Object Unknown Keys

问题描述

I'm currently building an application as a personal project that relies on fetching data from a server. I can successfully fetch the data however facing trouble when trying to decode. The problem I'm facing is that I don't know the keys for some of the objects until I receive them from the server. The data that I get back looks like this:

{
    "result": 0,
    "id": 1,
    "error": null,
    "data": {
        "UNKOWN_KEY": {
            "knownKey": "test",
            "knownKey": "test",
            "knownKey": "test",
        },
        "UNKOWN_KEY": {
            "knownKey": "test",
            "knownKey": "test",
            "knownKey": "test",
        },
        "UNKOWN_KEY": {
            "knownKey": "test",
            "knownKey": "test",
            "knownKey": "test",
        },
        "UNKOWN_KEY": {
            "knownKey": "test",
            "knownKey": "test",
            "knownKey": "test",
        }
    }
}

For the life of me I can't figure out how to decode those UNKOWN_KEYs and it's stopping me from progressing. I've tried using the following:

let dynamicContainer = try decoder.container(keyedBy: DeviceDataKey.self)

for key in dynamicContainer.allKeys {
    if let deviceData = try? dynamicContainer.decode(ACDeviceData.self, forKey: key) {
        data.insert(deviceData, at: 0)
    }
}

Any help that anyone can offer will be super appreciated. Thanks in advance.

标签: iosjsonrestswift4decodable

解决方案


您的值是具有类型键和值作为您的自定义模型"data"的字典。String如果您使用Codable,只需将类型指定data为字典

let data: [String: YourModel]

然后解码收到Data你的Response模型

struct Response: Decodable {
    let result, id: Int
    let error: String?
    let data: [String: YourModel]
}

struct YourModel: Decodable {
    let knownKey: String
}

如果您需要获取所有模型,只需compactMap在您的字典中使用

do {
    let decoded = try JSONDecoder().decode(Response.self, from: data)
    let models = decoded.data.compactMap { $0.value }
} catch { print(error) }

推荐阅读