我想从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]
我如何得到&#34;输入&#34;因为我正在获取状态并使用segue但现在我想获取状态以及类型以使用segue而我无法获取类型 任何帮助将不胜感激
答案 0 :(得分:1)
我认为在json中转换数据会给出正确的json格式的string,array&amp;字典。这就是为什么它会在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)")