Swift 4: Keeping the same order when parsing a JSON

前端 未结 2 1454
臣服心动
臣服心动 2021-01-25 13:05

I need to show a list of addresses in my app while keeping the same order as the response JSON. It looks something like this:

{
\"addresses\": {
    \"e5fdb5ba-7         


        
2条回答
  •  心在旅途
    2021-01-25 14:07

    as rmaddy says in their comment, the JSON you posted is a dictionary. Dictionaries are inherently unordered, so the order you get from the back-end is not guaranteed either. Some server implementations may give a consistent order and some may not.

    If you want a certain order you will need to change the back-end system to use an array rather than a dictionary.

    If you have no control of the client side and still want to preserve the order of the keys from the JSON, you will probably have to parse the JSON yourself manually, build an array of the keys, and then use those keys to fetch the items from the dictionary in that order.

提交回复
热议问题