我正在尝试使用Swift托管的JSON文件中读取“名称”的数据,而且似乎只能读取整个JSON文件,而无法选择特定的数据。我的JSON文件包含以下内容:
[{"Email":"Admin@admin.com","Password":"password","Name":"Admin"}]
我正在使用的快速代码是这样:
override func viewDidLoad() {
super.viewDidLoad()
//to get data from external DB
let url = URL(string: "http://localhost/Projects/Test_mobileAPI/test_userInfo.php?email=Admin@admin.com")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil{
print("Error Occured")
}
else{
print("Okie")
if let content = data {
do{
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print("this part works")
print(myJson)
if let diction = myJson as? NSDictionary
{
if let name = myJson["Name"]{
print(name as Any)
}
}
}
catch{
print(error)
}
}
}
}
task.resume()
}
我不断得到的输出是这样:
Okie
this part works
(
{
Email = "Admin@admin.com";
Name = Admin;
Password = password;
}
)
但是我不仅仅获得“名称”的值。谁能帮助我获取“名称”(即“管理员”)的值
答案 0 :(得分:-1)
你能尝试
if let myJson = try JSONSerialization.jsonObject(with: content) as? [[String:Any]] {
if let first = myJson.first {
print(first["Name"])
}
}
答案 1 :(得分:-2)
问题是您收到的不是字典的JSON,它是其中包含字典的单个元素数组。所以当你这样做
if let diction = myJson as? NSDictionary
myJson对象无法强制转换为NSDictionary。如果先解开数组,则应该可以引用字典并选择所需的任何键值:
if let array = myJson as? NSArray
{
if let myDict = array[0] as? NSDictionary
{
if let name = myDict ["Name"]{
print(name as Any)
}
}
}