如何从swift2中的json读取数据

时间:2016-04-27 11:41:29

标签: json swift

我正在尝试从swift(2.2)中的json文件中读取电子邮件,这是:

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

但我收到错误"错误域= NSCocoaErrorDomain代码= 3840"字符128周围未转义的控制字符。" UserInfo = {NSDebugDescription =字符128周围未转义的控制字符。}"我已经看过早些时候的帖子,但无法找到确切的问题在哪里?

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)")
            }

        }
    }

提前致谢!

2 个答案:

答案 0 :(得分:5)

  

"密码":"密码“

应该是

  

"密码":"密码"

您的字符无效,而不是"

<强>更新

现在您已修复了无效字符,您可以访问您的数据。但是,如果我相信你向我们展示的JSON摘录,那你就试图将NSDictionary作为一个实际上是阵列的东西。

所以你应该在do

中做这样的事情
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String: String]] {
    for jsonDictionary in jsonResult {
        if let person = jsonDictionary["email"] {
            print(person)
        }
    }
}

更新并修复

if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] {
    if let employees = jsonResult["Employees"] as? [[String:String]] {
        for employee in employees {
            if let person = employee["email"] {
                print(person)
            }
        }
    }
}

答案 1 :(得分:0)

您正尝试直接从字典中访问电子邮件密钥。而你需要首先从密钥&#34;员工&#34; &安培;那么你需要从&#34;电子邮件&#34;获得价值。键。

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"] as! String
                print(strEmail)
            }
        }

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

}