Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in a JSON File Using Swift

I'm really struggling with trying to read a JSON file into Swift so I can play around with it. I've spent the best part of 2 days re-searching and trying different methods but no luck as of yet so I have signed up to StackOverFlow to see if anyone can point me in the right direction.....

My JSON file is called test.json and contains the following:

{   "person":[      {        "name": "Bob",        "age": "16",        "employed": "No"      },      {        "name": "Vinny",        "age": "56",        "employed": "Yes"      }   ] }     

The file is stored in the documents directly and I access it using the following code:

let file = "test.json" let dirs : String[] = NSSearchPathForDirectoriesInDomains(                                                           NSSearchpathDirectory.DocumentDirectory,                                                           NSSearchPathDomainMask.AllDomainMask,                                                           true) as String[]  if (dirs != nil) {     let directories: String[] = dirs     let dir = directories[0]     let path = dir.stringByAppendingPathComponent(file) }  var jsonData = NSData(contentsOfFile:path, options: nil, error: nil) println("jsonData \(jsonData)" // This prints what looks to be JSON encoded data.  var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? NSDictionary  println("jsonDict \(jsonDict)") - This prints nil.....  

If anyone can just give me a push in the right direction on how I can de-serialize the JSON file and put it in an accessible Swift object I will be eternally grateful!

Kind Regards,

Krivvenz.

like image 815
Krivvenz Avatar asked Jun 25 '14 14:06

Krivvenz


People also ask

What is JSON decoder in Swift?

An object that decodes instances of a data type from JSON objects.


2 Answers

Follow the below code :

if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json") {     if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)     {         if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary         {             if let persons : NSArray = jsonResult["person"] as? NSArray             {                 // Do stuff             }         }      } } 

The array "persons" will contain all data for key person. Iterate throughs to fetch it.

Swift 4.0:

if let path = Bundle.main.path(forResource: "test", ofType: "json") {     do {           let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)           let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)           if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {                     // do stuff           }       } catch {            // handle error       } } 
like image 123
Abhishek Avatar answered Sep 19 '22 13:09

Abhishek


If anyone is looking for SwiftyJSON Answer:
Update:
For Swift 3/4:

if let path = Bundle.main.path(forResource: "assets/test", ofType: "json") {     do {         let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)         let jsonObj = try JSON(data: data)         print("jsonData:\(jsonObj)")     } catch let error {         print("parse error: \(error.localizedDescription)")     } } else {     print("Invalid filename/path.") } 
like image 42
Aks Avatar answered Sep 21 '22 13:09

Aks