Swift json decoding loses json object key order

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

I have a simple JSON object:

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


        
2条回答
  •  醉话见心
    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.

提交回复
热议问题