简体   繁体   English

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

[英]Parse Nested Array in JSON in Swift

I'm trying to Parse JSON with code and structure like this: 我正在尝试使用以下代码和结构解析JSON:

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

      }

Here is Json Structure 这是Json Structure

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

I've tried code like this: 我试过这样的代码:

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

But this results in the error "NSArray?" is not convertible to StringLiteralConvertible 但这会导致错误"NSArray?" is not convertible to StringLiteralConvertible "NSArray?" is not convertible to StringLiteralConvertible If I remove the optional and add the ! "NSArray?" is not convertible to StringLiteralConvertible如果我删除可选项并添加! force unwrap to the closure signature then this error goes away. 强制解开闭包签名,然后该错误消失。 However, I've seen instances where my app was crashing if something wrong came from the backend. 但是,我曾见过一些实例,如果后端出了问题,我的应用就会崩溃。 So my questions are: 所以我的问题是:

  1. Is there a way to parse this JSON and still keep the optional NSDictionary in the closure signature. 有没有一种方法可以解析此JSON,并且仍将可选NSDictionary保留在闭包签名中。

  2. Or do I just need to check if the dictionary is not nil and then proceed with the code I posted above? 还是我只需要检查字典是否不为零,然后继续上面发布的代码?

You can use "nil coalescing" to access the key in the Optional dictionary by adding a ? 您可以通过添加“ ? ”来使用“零合并”来访问“可选”字典中的键? between the dictionary variable and its subscript, like this: 在字典变量及其下标之间,如下所示:

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

With this syntax the evaluation will not try to access the key if responseDict is nil. 使用这种语法,如果responseDict为nil,则评估将不会尝试访问密钥。

The easiest way to do this is to use a library. 最简单的方法是使用库。

1) You can use swiftyJSON. 1)您可以使用swiftyJSON。 It uses the objective C JSON parsing library. 它使用目标C JSON解析库。 https://github.com/SwiftyJSON/SwiftyJSON https://github.com/SwiftyJSON/SwiftyJSON

2) If you want a library which uses a pure swift parser try JSONSwift. 2)如果要使用纯Swift解析器的库,请尝试JSONSwift。 The readme on github shows how you can retrieve nested values from the JSON file. github上的自述文件显示了如何从JSON文件中检索嵌套值。 And integrating it in your project just requires you to import a single file. 并将其集成到项目中仅需要您导入一个文件。 https://github.com/geekskool/JSONSwift https://github.com/geekskool/JSONSwift

Try to use objectForKey to retrive the data from the dictionary, like so: 尝试使用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