I have a simple JSON object:
{
\"values\": {
\"a\":\"\",
\"b\":\"\",
\"c\":\"\",
\"d\":\"\",
\"e\":\"\"
}
}
<
Back to the old fashion way, use JSONSerialization.jsonObject(with: Data, options: JSONSerialization.ReadingOptions) -> Any
.
It does keep order..... UNTIL you cast json?["values"]
into a [String: Any]
. At this time what Cezar says in the above answer enters the scene: dictionaries are unordered.
The following screenshot shows that, until json?["values"]
is an Any
, the order is kept in the string description.
This is not a Swift limitation per se. Both Swift and JSON Dictionaries are unordered. The JSON format does not guarantee key ordering, and as such, does not require parsers to preserve the order.
If you need an ordered collection, you'd be better off with returning an array of key-value pairs in the JSON:
{
"values": [
{"a" : ""},
{"b" : ""},
{"c" : ""},
{"d" : ""},
{"e" : ""}
]
}
And then store the keys in the right order to be able to iterate over them as you wish.