繁体   English   中英

如何在Swift4中访问JSON响应中的特定数据

[英]How to access specific data in a JSON response in Swift4

这是我得到响应的代码,我想使用一些值,因为我这样写,但是错误来了

let id = json["emp_id"] as! [String:Any]
let parameters = [
        "email": empEm,
        "password":"1234"
        ] as [String : Any]
    guard let url = URL(string: "http://localhost:8080/company/employee/login") else { return }
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
    request.httpBody = httpBody


    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }

        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
                let id = json["emp_id"] as! [String:Any]


            } catch {
                print(error)
            }
        }

        }.resume()

我的回应是

{
    available = 3;
    compoff = 0;
    displayname = Vamsi;
    "emp_id" = 001;
    gender = Male;
    id = 1;
    leaves = 4;
    rating = 0;
    star = 0;
    "termination_date" = active;
    wfh = 0;
}

我想从响应中获取id,emp_id之类的详细信息

您需要像这样解码JSON:

let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]

JSONSerialization.jsonObject的返回值为Any ,因此您需要特别告诉编译器JSON代表哪种对象。 您的情况是字典,因此请使用[String: Any]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM