Swift Codable: Is it possible to get dictionary key:values in order returned in json response?

Viewed 296

I am getting JSON response like this

"dict": [ 
   "key1" : "val1", 
   "key2" : "val2", 
   ...
]

Server always returns this dict in ordered manner key1, key2, ... Is it possible to parse this dict in ordered manner.

I can use

try container.decode([String: String].self, forKey: .dict)

But this is unordered parsing

I try also getting nested container like

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)
    }
}

But KeyedDecodingContainer<DynamicCodingKey> also seems to store unordered keys when I get them using .allKeys like standard HashTable.

1 Answers

Server always returns this dict in ordered manner key1, key2, ... Is it possible to parse this dict in ordered manner.

No. Dictionaries are inherently unordered collections. If you get the array of keys from the dictionary, they might happen to come back in the same order that they're in the JSON. That might even happen consistently. But you shouldn't count on it because, again, dictionaries are unordered collections. If you're relying on a particular order, then you should have the server send an array instead of a dictionary.

Related