繁体   English   中英

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

[英]Parse Nested Array in JSON in 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 "NSArray?" is not convertible to StringLiteralConvertible如果我删除可选项并添加! 强制解开闭包签名,然后该错误消失。 但是,我曾见过一些实例,如果后端出了问题,我的应用就会崩溃。 所以我的问题是:

  1. 有没有一种方法可以解析此JSON,并且仍将可选NSDictionary保留在闭包签名中。

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

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

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

使用这种语法,如果responseDict为nil,则评估将不会尝试访问密钥。

最简单的方法是使用库。

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

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

尝试使用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()
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM