JSON中的有序字典 [英] Ordered Dictionary in JSON

查看:321
本文介绍了JSON中的有序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有3个字符串变量

public var userLoginId : String?
public var searchString : String?
public var tableName : String?

我有字典:

let dict = ["userLoginId" : userLoginId, "searchString" : searchString,"tableName" : tableName]

现在,我通过JSON对其进行序列化:

Now I serialize it by JSON:

let data =  try! JSONSerialization.data(withJSONObject: dict, options :[])
let jsonstring = String(data:data, encoding:.utf8)!

jsonstring中,每次我得到如下所示的无序JSON:

In jsonstring, every time I get an unordered JSON like below:

"{\"tableName\":\"null\",\"userLoginId\":\"Dilip\",\"searchString\":\"Tata\"}"

如何获得为字典分配值的相同格式?

How can I get in the same format in which I assigned value to dictionary?

推荐答案

按照标准,Swift的Dictionary不仅没有排序,而且JSON字典也没有.您可能最好的办法是将密钥以正确的顺序存储在数组中.您无需迭代字典,而可以迭代键的有序数组,然后使用这些键从字典中获取.

Not only does Swift's Dictionary not have ordering, but neither do JSON dictionaries, as per the standard. The best you could probably do is store the keys, in correct order, in an array. Instead of iterating the dictionary, you instead iterate the ordered array of keys, and then fetch from the dictionary with those keys.

为避免手动重复键,您可以将字典表示为(Key, Value)元组的数组,如下所示:

To avoid repeating the keys manually, you can express your dictionary as an array of (Key, Value) tuples, like so:

let keyValuePairs = [
    ("userLoginId", userLoginId),
    ("searchString", searchString),
    ("tableName", tableName)
]

然后,您可以使用这个漂亮的Dictionary扩展名,从这些(Key, Value)元组创建一个新的Dictionary:

Then you can use this nifty Dictionary extension, to create a new Dictionary from those (Key, Value) tuples:

extension Dictionary {
    init(_ keyValuePairs: [(Key, Value)]) {
        self.init(minimumCapacity: keyValuePairs.count)

        for (key, value) in keyValuePairs {
            self[key] = value
        }
    }
}

let dict = Dictionary(keyValuePairs)
let orderedKeys = keyValuePairs.map{ $0.0 }

现在,您可以在Swift代码中使用orderedKeys,或将它们与dict一起存储在JSON中:

Now you can use the orderedKeys in your Swift code, or store them in JSON alongside the dict:

print("Example usage:")
for key in orderedKeys {
    let value = dict[key]!

    print("\(key): \(value)")
}

这篇关于JSON中的有序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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