Arrays 在Swift中编码和解码字符串数组的JSON字典
我正在编写一个部分依赖于大型数组字典的Swift应用程序。摘录如下:Arrays 在Swift中编码和解码字符串数组的JSON字典,arrays,json,dictionary,swift2,Arrays,Json,Dictionary,Swift2,我正在编写一个部分依赖于大型数组字典的Swift应用程序。摘录如下: let arithmeticalDict:Dictionary<String, Array <String>> = [ "1116": [], "1117": [], "1118": ["(1+1+1)*8"], "1128": ["1*(1 + 2)*8","(1 + 2)/(1/8)"] ] let算术词典= [ "1116": [], "1117": [], "1
let arithmeticalDict:Dictionary<String, Array <String>> =
[
"1116": [],
"1117": [],
"1118": ["(1+1+1)*8"],
"1128": ["1*(1 + 2)*8","(1 + 2)/(1/8)"]
]
let算术词典=
[
"1116": [],
"1117": [],
"1118": ["(1+1+1)*8"],
"1128": ["1*(1 + 2)*8","(1 + 2)/(1/8)"]
]
我认为将其放入JSON资源可能更容易管理,我以前在小型简单字典中使用过这种技术。这个案例更大,715个条目占用了磁盘上大约370Kb的空间。但是,在这种情况下,我遇到了两个问题:
字典中1-您的字典已经键入,它是
字典
,因此您只需使用NSJSONSerialization来创建JSON数据:
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(arithmeticalDict, options: NSJSONWritingOptions.PrettyPrinted)
// now you can export "jsonData" to a file
} catch {
print(error)
}
2-要解码保存的JSON对象,只需再次使用相同的类型:
do {
if let dict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String:[String]] {
print(dict) // ["1118": ["(1+1+1)*8"], "1117": [], "1116": [], "1128": ["1*(1 + 2)*8", "(1 + 2)/(1/8)"]]
}
} catch {
print(error)
}