Reputation: 2330
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:
Is there a way to parse this JSON and still keep the optional NSDictionary in the closure signature.
Or do I just need to check if the dictionary is not nil and then proceed with the code I posted above?
Upvotes: 0
Views: 3374
Reputation: 70097
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.
Upvotes: 1
Reputation: 14845
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()
}
Upvotes: 0
Reputation: 6495
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
Upvotes: 0