0

Here is my code I am getting response and I want to use some values in that I wrote like this but error is coming

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()

my response is

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

I want to take details like id, emp_id from the response

3
  • What "error is coming"? Show us the error. Also, the response you posted is not valid JSON. Commented Jul 5, 2019 at 7:57
  • Type 'Any' has no subscript members in this line. let id = json["emp_id"] as! [String:Any] Commented Jul 5, 2019 at 7:58
  • This has been asked 100000 times. You have to cast the result: let json = try JSONSerialization.jsonObject(with: data) as! [String:Any] And the value of emp_id is string. let id = json["emp_id"] as! String Commented Jul 5, 2019 at 8:02

1 Answer 1

1

You need to decode your JSON like this:

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

The return value of JSONSerialization.jsonObject is Any, so you need to tell the compiler specifically what kind of object the JSON represents. In your case it is a dictionary, so use [String: Any]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.