解析JSON使用斯威夫特/ SwiftyJSON
问题描述:
我已经按照这个几个教程,而据我可以告诉我做的应该是工作的内容。我有一个API呼叫下面的JSON响应解析JSON使用斯威夫特/ SwiftyJSON
{
"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值是否为空。下面是我使用
的资源的代码返回类型为JSON
ApiConnector.sharedInstance.login(emailText.text!, password: passwordText.text!) { (res) in
if let id = res["Id"] as? String {
if id != "" {
}
else
{
}
}
}
我收到来自“JSON”到不相关类型的“字符串”总是失败说演员的警告。
什么我需要改变看id的值?
这是您使用的手柄JSON什么库ApiConnector类
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)
})
}
答
我想你想是这样的:
ApiConnector.sharedInstance.login(emailText.text!, password: passwordText.text!) { (res) in
if let id = res["Id"].string {
// Do something.
}
}
答
的代码?如果迅速json你可以做类似
res["id"]?.string
如果你没有说什么“res”的类型,我们不能回答你。
对不起,完全隔开一点。我编辑了标题以反映它。我正在使用SwiftyJSON – Jhorra
res返回类型是JSON。我也用这些信息更新了我的问题。 – Jhorra