Swift Codable:是否可以按顺序在json响应中获取字典key:values?

问题描述

我正在收到这样的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)
    }
}

但是当我使用KeyedDecodingContainer<DynamicCodingKey>像标准HashTable一样获得.allKeys时,似乎也存储了无序键。

解决方法

服务器始终以有序方式返回此字典key1,key2,...是否有可能以有序方式解析此字典。

否。词典本质上是无序的集合。如果您从字典中获得键数组,则它们可能碰巧以与JSON中相同的顺序返回。这甚至可能会持续发生。但是您不应该指望它,因为字典又是无序的集合。如果您要依靠特定的顺序,那么应该让服务器发送一个数组而不是一个字典。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...