如何访问标识符根据Swift中的responsetype而变化的JSON响应?
我有一个JSON查询,它返回一个成功结果和一个失败结果 但是,在这些情况下,标识符是不同的 案例A)成功结果如何访问标识符根据Swift中的responsetype而变化的JSON响应?,json,swift,Json,Swift,我有一个JSON查询,它返回一个成功结果和一个失败结果 但是,在这些情况下,标识符是不同的 案例A)成功结果 { result = { "created_at" = "2016-07-25T11:44:26.816Z"; "created_by" = ol; "display_name" = aaaa; email = aaaa; "fb_id" = "<null>"; pwd = aaaa; roles =
{
result = {
"created_at" = "2016-07-25T11:44:26.816Z";
"created_by" = ol;
"display_name" = aaaa;
email = aaaa;
"fb_id" = "<null>";
pwd = aaaa;
roles = (
stu
);
schools = "<null>";
};
}
对于案例A),我访问以下元素:
//access the inner array from the json answer called result
if let response = responseObject as? NSDictionary {
self.userCredentials = (response as? NSDictionary)!
print("user Credentials print: ")
print(self.userCredentials)
print("user credentials size")
print(self.userCredentials.count)
if let displayName = response["result"]!["display_name"] as? String {
print(displayName)
}
if let email = response["result"]!["email"] as? String {
print(email)
}
if let password = response["result"]!["pwd"] as? String {
print(password)
但如果出现标识符为“info”的JSON,应用程序就会崩溃。
我试着和你一起去
if(response["info"].isEmpty)
但这是行不通的
如果返回案例B)中的JSON,如何防止代码解析值?尝试使用
where
:
if let response = responseObject as? NSDictionary where response["info"] == nil {
// rest of your code
}
您的应用程序崩溃,因为您正在使用以下命令强制展开结果:
response["result"]!["display_name"]
相反,请使用可选绑定安全地展开并找出得到的响应:
if let response = responseObject as? [String:AnyObject] {
if let result = response["result"] as? [String:AnyObject] {
// work with the content of "result", for example:
if let displayName = result["display_name"] {
print(displayName)
}
} else if info = response["info"] as? String {
// print the info string
print(info)
} else {
// handle the failure to decode
}
}
您的应用程序崩溃,因为您正在强制展开json值:
response["result"]!["display_name"]
and so on..
因此,如果响应失败,您基本上是在强制应用程序崩溃
一种解决方案是可以在if-let块中安全地展开值
Example:
let x = [
"created_at" : "2016-07-25T11:44:26.816Z",
"Inner_dict" : ["value":"MYVALUE"]
]
if let dic = x["Inner_dict"] as? [String:String], val = dic["value"] {
print(val)
}
更好的解决方案可能是,服务器根据成功/失败为响应设置不同的状态代码。当然,只有在您可以编辑服务器端时,此解决方案才能正常工作。Thx。这个解决方案对我来说是最容易理解的。效果很好
Example:
let x = [
"created_at" : "2016-07-25T11:44:26.816Z",
"Inner_dict" : ["value":"MYVALUE"]
]
if let dic = x["Inner_dict"] as? [String:String], val = dic["value"] {
print(val)
}