Livioso
Livioso

Reputation: 1252

Swift issue with JSON / NSJSONSerialization

I'm trying to read this JSON file in Swift and store the data in a NSDictionary where I want to have the name as key and the directory as value.

{
 "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"}
 ]
}

In order to achieve this I'm using 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

So far I can read in the file and the resulting NSDictionary looks like ["subjects, "7 objects"]. Unfortunately I'm clueless how I can achieve what I actually need ("NSDictionary with name as key and directory as value").

Upvotes: 0

Views: 362

Answers (1)

iain
iain

Reputation: 5683

You can extract the required data like so

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
}

Upvotes: 1

Related Questions