Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 在Swift中编码和解码字符串数组的JSON字典_Arrays_Json_Dictionary_Swift2 - Fatal编程技术网

Arrays 在Swift中编码和解码字符串数组的JSON字典

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

我正在编写一个部分依赖于大型数组字典的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": [],
"1118": ["(1+1+1)*8"],
"1128": ["1*(1 + 2)*8","(1 + 2)/(1/8)"]
]
我认为将其放入JSON资源可能更容易管理,我以前在小型简单字典中使用过这种技术。这个案例更大,715个条目占用了磁盘上大约370Kb的空间。但是,在这种情况下,我遇到了两个问题:

  • 如何在JSON文件中指定字典中的每个键对应一个字符串数组(其中数组长度不规则,有些可能不包含任何内容)

  • 在Swift中加载JSON文件时,如何将其提取到适当的
    字典中


  • 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)
    }