S. Bharti S. Bharti - 7 months ago 79
Swift Question

how to read data from json in swift2

I am trying to read email from a json file in swift(2.2) which is:

{ "employees" : [
{
"name": "sudhanshu",
"email": "sudhanshu.bharti@digitalavenues.com",
"password": "password"
"profilePic": ""
},
{
"name": "prokriti",
"email": "prokriti.roy@digitalavenues.com",
"password": "password@123",
"profilePic": ""
}
]}


But i am getting error " Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character around character 128." UserInfo={NSDebugDescription=Unescaped control character around character 128.}" i have seen earlier posts but unable to find where exactly problem is??

if let path = NSBundle.mainBundle().pathForResource("Employees", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
do {
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

if let error = jsonResult["error"] {
print("Error is: \(error)")
} else {
if let person = jsonResult["email"] {
print(person) // dictionary[@"quotables"]
}
}

} catch let error as NSError {
print("Error is: \(error)")
}

}
}


Thanks in advance!

Answer

Hi Please try below code

if let path = NSBundle.mainBundle().pathForResource("Employees", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
    do {
        let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

        if let error = jsonResult["error"] {
            print("Error is: \(error)")
        } else {
            let person = jsonResult["employees"] as! NSArray
            for i in 0..<person.count
            {
                let dict = person.objectAtIndex(i) as! NSDictionary
                let strEmail = dict["email"]
                print(strEmail)
            }
        }

    } catch let error as NSError {
        print("Error is: \(error)")
    }

}