【问题标题】:Swift issue with JSON / NSJSONSerializationJSON / NSJSONSerialization 的 Swift 问题
【发布时间】:2014-06-28 15:58:28
【问题描述】:

我正在尝试在 Swift 中读取此 JSON 文件并将数据存储在 NSDictionary 中,我希望将 name 作为 key 和 directory 作为

{
 "subjects": [
  { "prefix":"", "name":"mada" , "directory":"E1862_Unterrichte_I/E1862_2iCa" },
  { "prefix":"", "name":"oopI2" , "directory":"E1862_Unterrichte_I/E1862_2iCa" },
  { "prefix":"", "name":"req" , "directory":"E1862_Unterrichte_I/E1862_2iCa" },
  { "prefix":"", "name":"ws2C" , "directory":"E1862_Unterrichte_I/E1862_2iCb" },
  { "prefix":"", "name":"sprx" , "directory":"E1868_Unterrichte_Kontext/E1868_8KKa15" },
  { "prefix":"", "name":"etw", "directory":"E1868_Unterrichte_Kontext/E1868_8KEd" },
  { "prefix":"", "name":"infre", "directory":"E1868_Unterrichte_Kontext/E1868_8KGc"}
 ]
}

为了实现这一点,我正在使用 NSJSONSerialization

let data = NSData.dataWithContentsOfFile("subjects.json", options: .DataReadingMappedIfSafe, error: nil)

var error: NSError?
let jsonDict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSDictionary

到目前为止,我可以读取文件,结果 NSDictionary 看起来像 ["subjects, "7 objects"]。不幸的是,我对如何实现我真正需要的东西一无所知("NSDictionary with name as key and directory as value").

【问题讨论】:

    标签: json swift nsjsonserialization


    【解决方案1】:

    您可以像这样提取所需的数据

    if let subjects = jsonResult["subjects"] as? NSDictionary[] {
        for subject in subjects {
            // subject is an NSDictionary
            var prefix = subject["prefix"] as String
            var name = subject["name"] as String
            // etc
        }
    } else {
        // There was no 'subjects' key in the dictionary
    }
    

    【讨论】:

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