我正在尝试在Swift中读取此JSON文件,并将数据存储在NSDictionary中,我想将name作为键并将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”)。

最佳答案

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

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
}

关于json - JSON/NSJSONSerialization的快速问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24468546/

10-09 00:24