0

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 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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.