Swift 4: Keeping the same order when parsing a JSON

前端 未结 2 1424
臣服心动
臣服心动 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 13:50

    If the order of your data is important you should put it into an Array, not a Dictionary (which is inherently without order but with quick keyed access as others have noticed). Please change your backend accordingly and ask another question if it does not work.

    0 讨论(0)
  • 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.

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