user3766930 user3766930 - 14 days ago 6
Swift Question

After casting json data to [[String: AnyObject]] it seems to be empty - why?

I'm calling my webservice with

alamofire
and trying to parse the json result.

My code looks like this:

Alamofire.request("\(serverURL)/users/\(username)/hashtags")
.validate()
.responseJSON { response in
switch response.result {
case .success:
DispatchQueue.main.async(execute: {
print(response.result.value!)

if let jsonData = response.result.value as? [[String: AnyObject]] {
print("this is not printed")


The first print returns:

{
hashtags = (
test,
elo
);
}


and the 2nd one is not printed at all - the code is never executed. Why?

When I call my webservice in the browser I'm getting:

{"hashtags":["test","test2"]}

Answer

The JSON structure you are trying to convert is a dictionary not an array. You are trying to convert the response to an array of dictionary and that's why it is failing.

You need to use:

if let jsonData = response.result.value as? [String: AnyObject]
{
   // Handle data
}