我想从JSON对象中获取数组
这是我的代码:
let url = URL(string:"http://192.168.0.117/rest/login.php")
let parameters = ["email": email , "pwd":password]
var request = URLRequest(url : url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject:parameters, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
session.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
do {
let json = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
if let json = json {
print("HERE SHOULD BE YOUR JSON OF LOGIN : \(json)")
let status = json["status"] as! String
let datas = json["data"] as! String
print("Here is the Data : \(datas)")
print("here LOIGN : \(status)")
if status == "200"
{
DispatchQueue.main.async
{
self.performSegue(withIdentifier: "dosigninEmp", sender: self)
}
} else if status == "204"
{
self.displayMessage(userMessage: "Not Authorized User")
}
}
}
} else {
print("Error \(String(describing: error?.localizedDescription))")
}
}).resume()
我得到的输出是:
HERE SHOULD BE YOUR JSON OF LOGIN : ["status": 200, "data": {
"emp_id" = 1004;
type = emp;
}, "Message": Auth Succesful]
我如何获得“类型”因为我正在获取状态并使用 segue 但现在我想获取状态以及类型以使用 segue 但我无法获得类型 任何帮助将不胜感激
最佳答案
我认为将您的数据转换为 json 将提供正确的 json 格式的字符串、数组和字典。这就是为什么它会在 Dictionary
中提供数据:
print("HERE SHOULD BE YOUR JSON OF LOGIN : \(json)")
let status = json["status"] as! String
let datas = json["data"] as! String
print("Here is the Data : \(datas)")
print("here LOIGN : \(status)")
可以将这些行改成:
var type = ""
var datas = [String: AnyObject]()
if let data = json["data"] as? [String: AnyObject], let typeStr = data["type"] as? String {
datas = data
type = typeStr
}
print("Here is the Data : \(datas)")
print("Here Type : \(type)")
关于ios - 如何快速获取json对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49606731/