我正在尝试在 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的名称为键,目录为值”)。
答案 0 :(得分: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
}