Zachary Bell
Zachary Bell

Reputation: 610

Alamofire in iOS is Receiving Dictionary Instead of Array

I am working on creating tables in iOS and am supposed to be receiving the required data in the form of JSON arrays. However, when I get the data in my iOS app it is presented as an unsorted dictionary instead. I was able to run the GET request in Postman and receive the data correctly, but when I receive it through Alamofire in my iOS app it is not formatted correctly. Is it possible that Alamofire would reformat the JSON somehow and convert all arrays to dictionaries, and can I override that setting somehow?

Here is an example of the column section of the JSON in Postman:

enter image description here

And here is what I am receiving through Alamofire:

enter image description here

This is how I am attempting to access the JSON

if let jsonColumns = json["columns"] as? [[String:Any]] {
        for columns in jsonColumns {
            for column in columns.values {
                if let c = column as? [String:Any] {
                    if c["isVisible"] as? Bool == false {
                        continue
                    }
                    if let columnName = c["name"] as? String {
                        dataSet.columns.append(columnName)
                    }
                }
            }
        }
    }

Upvotes: 3

Views: 410

Answers (2)

alxlives
alxlives

Reputation: 5212

Alamofire ObjectMapper order the parameters alphabetically.

You can change the JSON to be an Array of columns, like this:

 { "columns" : [ 
     {"name": "1", "visible": false},
     {"name": "2", "visible": false},
     {"name": "3", "visible": true}
]}

This way would solve the sorting problem.

Upvotes: 1

LorenzOliveto
LorenzOliveto

Reputation: 7936

The structure of the JSON in the 2 images are the same, you have columns that's an array of dictionaries ([[String: Any]]) that has only one element.

Values on the dictionary are not sorted because they are meant to be accessed by key and not by cycling through the values.

From here:

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word.

Upvotes: 2

Related Questions