【问题标题】:How to access specific data in a JSON response in Swift4如何在 Swift4 中访问 JSON 响应中的特定数据
【发布时间】:2019-07-05 07:57:00
【问题描述】:

这是我收到响应的代码,我想在其中使用一些值 我是这样写的,但是错误来了

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。
  • Type 'Any' 在此行中没有下标成员。让 id = json["emp_id"] 为! [字符串:任何]
  • 这已被问了 100000 次。您必须转换结果:let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]emp_id 的值是字符串。 let id = json["emp_id"] as! String

标签: ios swift jsonresponse


【解决方案1】:

您需要像这样解码您的 JSON:

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

JSONSerialization.jsonObject的返回值是Any,所以需要具体告诉编译器这个JSON代表什么样的对象。在你的情况下它是一本字典,所以使用[String: Any]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2016-07-17
    • 2019-01-12
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多