本文介绍了使用Swift/SwiftyJSON解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经遵循了一些教程,据我所知我应该在做什么.我有来自api调用的以下json响应
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": "[email protected]",
"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
}]
}
基本上,我只想检查Id值是否为空.这是我正在使用的代码
Essentially I just want to check if the Id value is blank or not. Here is the code I'm using
res返回类型为JSON
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
{
}
}
}
我得到一条警告,提示从'JSON'转换为不相关的类型'String'总是失败.
I get a warning that says Cast from 'JSON' to unrelated type 'String' always fails.
我需要更改什么才能看到Id的值?
What do I need to change to see the value of Id?
这是ApiConnector类中的代码
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)
})
}
推荐答案
我认为您想要这样的东西:
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.
}
}
这篇关于使用Swift/SwiftyJSON解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!