简体   繁体   中英

Parse Nested Array in JSON in Swift

I'm trying to Parse JSON with code and structure like this:

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

      }

Here is 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 If I remove the optional and add the ! 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.

  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.

The easiest way to do this is to use a library.

1) You can use swiftyJSON. It uses the objective C JSON parsing library. https://github.com/SwiftyJSON/SwiftyJSON

2) If you want a library which uses a pure swift parser try JSONSwift. The readme on github shows how you can retrieve nested values from the JSON file. And integrating it in your project just requires you to import a single file. https://github.com/geekskool/JSONSwift

Try to use objectForKey to retrive the data from the dictionary, like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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