ios - 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_KEY
s 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.
解决方案
您的值是具有类型键和值作为您的自定义模型"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) }
推荐阅读
- node.js - 如何使 Google App Service 公开可见
- python - 将浮点数列表转换为熊猫中的多列浮点数
- spring-boot - 如何在我的 Spring Boot 2 应用程序中为资产管道(bertramlabs)配置静态版本控制(摘要)?
- c++ - virtual base classes initiailization
- apache-spark - spark parquet 读写中的类型更改支持
- java - 不理解 ExecutorService#shutdown
- python - 将图像(png和jpg)转换为多维列表并在python中向后转换
- c - CURL: send a notify(POST) while upload file
- c -
is my implementation of my strncpy right? - redux - Dispatching two sync actions