如何访问其标识符根据Swift中的响应类型而变化的JSON响应?

时间:2016-07-25 11:53:47

标签: 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 =         (
        stu
    );
    schools = "<null>";
};
}

案例B)失败

{
info = "DETAIL:  Key (email)=(aaaa) already exists.\n";
}

对于案例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)

但是如果JSON带有标识符&#34; info&#34;应用程序崩溃了。 我试着和

一起去
if(response["info"].isEmpty)

但这不起作用

如何在返回案例B的JSON的情况下阻止我的代码解析值?

3 个答案:

答案 0 :(得分:2)

你的应用程序崩溃是因为你强行打开结果:

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
    }
}

答案 1 :(得分:2)

你的应用程序崩溃是因为你强行解开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)
}

更好的解决方案可能是,服务器根据成功/失败为响应设置不同的状态代码。但是,当然,只有在您可以编辑服务器端时,此解决方案才有效。

答案 2 :(得分:1)

尝试where

if let response = responseObject as? NSDictionary where response["info"] == nil {
    // rest of your code
}