Jhorra Jhorra - 4 months ago 25
JSON Question

Parse JSON using Swift / SwiftyJSON

I've followed several tutorials on this, and as far as I can tell what I'm doing should be working. I have the following json response from an api call

{
"Id": "1",
"Name": "Test User",
"Email": "test@email.com",
"ProfileImage": null,
"IsAdmin": true,
"TakesJobs": false,
"IsLocationUser": false,
"IsCompanyAdmin": true,
"LocationUsers": [],
"CompanyUsers": [{
"CompanyName": "Test Company",
"Id": 6,
"CompanyId": 5,
"UserId": "1",
"Admin": true,
"TakesJobs": false,
"UserName": null,
"UserEmail": null,
"AssignedJobs": null
}]
}


Essentially I just want to check if the Id value is blank or not. Here is the code I'm using

The res return type is JSON

ApiConnector.sharedInstance.login(emailText.text!, password: passwordText.text!) { (res) in
if let id = res["Id"] as? String {
if id != "" {

}
else
{

}

}
}


I get a warning that says Cast from 'JSON' to unrelated type 'String' always fails.

What do I need to change to see the value of Id?

This is the code from the ApiConnector class

func login(username: String, password: String, onCompletion: (JSON) -> Void) {
let route = baseURL + "auth?Email=" + username + "&Password=" + password
makeHTTPPostRequest(route, body: ["Email":username, "Password": password], onCompletion: { json, err in
onCompletion(json as JSON)
})
}

Answer

I think you want something like this:

ApiConnector.sharedInstance.login(emailText.text!, password: passwordText.text!) { (res) in
    if let id = res["Id"].string {
      // Do something.
    }
}