Swift json decoding loses json object key order

后端 未结 2 775
梦谈多话
梦谈多话 2021-01-07 03:44

I have a simple JSON object:

{
    \"values\": {
        \"a\":\"\",
        \"b\":\"\",
        \"c\":\"\",
        \"d\":\"\",
        \"e\":\"\"
    }
}
<         


        
相关标签:
2条回答
  • 2021-01-07 04:00

    The following does not work so you don't waste time trying:

    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.

    0 讨论(0)
  • 2021-01-07 04:11

    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.

    0 讨论(0)
提交回复
热议问题