【问题标题】:Swift Codable: Is it possible to get dictionary key:values in order returned in json response?Swift Codable:是否可以按json响应中返回的顺序获取字典键:值?
【发布时间】: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


【解决方案1】:

服务器总是以有序的方式返回这个dict key1,key2,...是否可以按有序的方式解析这个dict。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多