Ezekiel
Ezekiel

Reputation: 2515

How can I read JSON file from disk and store to array in Swift

I want to read a file from Disk in a swift file. It can be a relative or direct path, that doesn't matter. How can I do that?

I've been playing with something like this

let classesData = NSData .dataWithContentsOfMappedFile("path/to/classes.json");

And it finds the file (i.e. doesn't return nil) but I don't know how to manipulate and convert to JSON, the data returned. It isn't in a string format and String() isn't working on it.

Upvotes: 0

Views: 1481

Answers (2)

eonil
eonil

Reputation: 85975

You can use good old Cocoa classes.

let p1  =   "/path/to/any.json"
let d1  =   NSData(contentsOfFile: p1)
let a1 : AnyObject! =   NSJSONSerialization.JSONObjectWithData(d1, options: NSJSONReadingOptions(0), error: nil)

println(a1)

Upvotes: 0

drewag
drewag

Reputation: 94723

You need to call NSJsonSerialization.JSONObjectWithData:

var error : NSError?
var json = NSJSONSerialization.JSONObjectWithData(classesData, options: nil, error: &error)

Upvotes: 2

Related Questions