Swift 4:解析JSON时保持相同的顺序 [英] Swift 4: Keeping the same order when parsing a JSON

查看:231
本文介绍了Swift 4:解析JSON时保持相同的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的应用程序中显示地址列表,同时保持与响应JSON相同的顺序.看起来像这样:

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-7afb-11e8-bead-43321d1a8905": {
        "contact": "Name1",
        "zipCode": "06100"
    },
    "1495b580-7afc-11e8-bead-9f4049791561": {
        "contact": "Name2",
        "zipCode": "06100"
    },
    "e5fdb5ba-7afb-11e8-bead-43321d1a8905": {
        "contact": "Name3",
        "zipCode": "06100"
    },
    "1495b580-7afc-11e8-bead-9f4049791561": {
        "contact": "Name4",
        "zipCode": "06100"
    }
  } 
}

但是当我使用

JSONSerialization.jsonObject(with: data, options: [])

地址的顺序混合在一起.有没有一种方法可以保持与JSON完全相同的顺序?

The order of the addresses gets all mixed up. Is there a way to keep the exact same order as the JSON?

推荐答案

您发布的JSON是一本字典.词典本质上是无序的,因此也无法保证您从后端获得的顺序.一些服务器实现可能给出一致的顺序,而某些则可能不一致.

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.

如果您无法控制客户端,但仍然希望保留JSON中键的顺序,则可能必须自己手动解析JSON,构建键数组,然后使用这些键进行操作以此顺序从字典中获取项目.

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.

这篇关于Swift 4:解析JSON时保持相同的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆