gpt4 book ai didi

ios - 在 Swift 中解析 JSON 中的嵌套数组

转载 作者:行者123 更新时间:2023-11-29 01:54:28 25 4
gpt4 key购买 nike

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

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

}

这是Json结构

   {
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?”不可转换为 StringLiteralConvertible 如果我删除可选并添加 !强制解包到闭包签名,然后此错误就会消失。但是,我见过如果后端出现问题,我的应用程序就会崩溃的情况。所以我的问题是:

  1. 是否有一种方法可以解析此 JSON,同时仍将可选的 NSDictionary 保留在闭包签名中。

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

最佳答案

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

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

使用此语法,如果 responseDict 为 nil,则评估将不会尝试访问 key 。

关于ios - 在 Swift 中解析 JSON 中的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31040836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com