在Swift中用JSON解析嵌套数组

时间:2015-06-25 03:43:03

标签: ios json swift

我正在尝试使用以下代码和结构来解析JSON:

    userApiService.getAllUsers { (responseDict:NSDictionary?, error:NSError?) -> Void in
   //Parse responseDict for the key "result"

      }

这是Json Structure

   {
        error = "";
        result =     (
                    {
                name = AnotherUser;
                password = AnotherPassword;
                userId = 1343;
            },
                    {
                name = TestUser;
                password = TestPassword;
                userId = 1344;
            },
                    {
                name = TestUser;
                password = TestPassword;
                userId = 1347;
            },
        );
        status = 200;
    }

我尝试过这样的代码:

 self.loadingIcon.endRefreshing()
            if let resultDict = responseDict["result"] as? NSArray {
                for userRecord in resultDict{
                    var userModel = User(userDict: userRecord as! NSDictionary)
                    self.tableData.append(userModel)
                }
            }
            self.tblView.reloadData()
        }

但这导致错误"NSArray?" is not convertible to StringLiteralConvertible如果我删除了可选项并添加了!强制解包到闭包签名然后这个错误就消失了。但是,我已经看到了如果后端出现错误,我的应用程序崩溃的情况。所以我的问题是:

  1. 有没有办法解析这个JSON,并且仍然在闭包签名中保留可选的NSDictionary。

  2. 或者我只需要检查字典是否为零,然后继续上面发布的代码?

3 个答案:

答案 0 :(得分:1)

你可以使用" nil coalescing"通过在字典变量及其下标之间添加?来访问Optional词典中的键,如下所示:

if let resultDict = responseDict?["result"] as? NSArray {
   // ...
}

如果responseDict为零,则评估不会尝试访问密钥。

答案 1 :(得分:0)

最简单的方法是使用库。

1)您可以使用swiftyJSON。它使用目标C JSON解析库。 https://github.com/SwiftyJSON/SwiftyJSON

2)如果你想要一个使用纯swift解析器的库,请尝试使用JSONSwift。 github上的自述文件显示了如何从JSON文件中检索嵌套值。将它集成到项目中只需要导入一个文件。 https://github.com/geekskool/JSONSwift

答案 2 :(得分:0)

尝试使用objectForKey来检索字典中的数据,如下所示:

 self.loadingIcon.endRefreshing()
            if let resultDict = responseDict.objectForKey("result") as? NSArray {
                for userRecord in resultDict{
                    var userModel = User(userDict: userRecord as! NSDictionary)
                    self.tableData.append(userModel)
                }
            }
            self.tblView.reloadData()
        }
相关问题