【发布时间】:2020-12-04 12:45:57
【问题描述】:
我收到这样的 JSON 响应
"dict": [
"key1" : "val1",
"key2" : "val2",
...
]
服务器总是以有序的方式返回这个字典 key1, key2, ... 是否可以按顺序解析这个字典。
我可以使用
try container.decode([String: String].self, forKey: .dict)
但这是无序解析
我也尝试获得类似的嵌套容器
try container.nestedContainer(keyedBy: DynamicCodingKey.self, forKey: .dict)
struct DynamicCodingKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(intValue: Int) {
self.intValue = intValue
self.stringValue = "\(intValue)"
}
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = Int(stringValue)
}
}
但是当我使用.allKeys 像标准哈希表一样获取无序键时,KeyedDecodingContainer<DynamicCodingKey> 似乎也存储了无序键。
【问题讨论】:
-
您发布的内容不是有效的 JSON。你的意思是
{ "dict": { ... } }? -
dicts 永远是一个无序的集合
-
新开发者是的,你是对的
标签: json swift codable decodable