【问题标题】:Encode and decode JSON dictionaries of arrays of strings in Swift在 Swift 中编码和解码字符串数组的 JSON 字典
【发布时间】:2016-01-02 10:02:57
【问题描述】:

我正在编写一个部分依赖于大型数组字典的 Swift 应用程序。摘录如下:

let arithmeticalDict:Dictionary<String, Array <String>> =
[
    "1116": [],
    "1117": [],
    "1118": ["(1+1+1)*8"],
    "1128": ["1*(1 + 2)*8","(1 + 2)/(1/8)"]
]

我认为将它放入 JSON 资源可能更易于管理,这是我以前用于小型、简单字典的一种技术。这种情况更大,715 个条目在磁盘上占用了大约 370Kb。但是在这种情况下,我遇到了两个问题:

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

  2. 在 Swift 中加载 JSON 文件时,如何将其提取到适当的 &lt;String, Array &lt;String&gt;&gt; 字典中?

【问题讨论】:

    标签: arrays json dictionary swift2


    【解决方案1】:

    1- 您的字典已经输入,它是Dictionary&lt;String, Array &lt;String&gt;&gt;,所以您只需使用 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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多