如何在swift2中从json读取数据 [英] how to read data from json in swift2
问题描述
我正在尝试从swift(2.2)中的json文件读取电子邮件:
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": ""
}
]}
但是我收到错误消息"Error Domain = NSCocoaErrorDomain Code = 3840"字符128附近的转义控制字符."UserInfo = {NSDebugDescription =字符128附近的转义控制字符.}"我见过较早的帖子,但找不到确切的位置问题是?
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)")
}
}
}
提前谢谢!
推荐答案
您正尝试直接从字典中访问电子邮件密钥.而您需要首先从关键员工"那里访问数组&那么您需要从电子邮件"键中获取价值.
You are trying to access directly email key from the dictionary. while you need to first access array from the key "employees" & then you need to get value from "email" key.
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)")
}
}
这篇关于如何在swift2中从json读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!