arcade16
arcade16

Reputation: 1535

How to store array of dictionaries into class variable?

I have an array of dictionaries that is being read in from a JSON file as seen below. I would like to store that value (jsonResult) into a class variable so that I can use it to populate a tableview. However, I don't quite understand how to store that value.

Here is how I am getting my array of dictionaries (jsonResult):

      if let path = Bundle.main.path(forResource: filename, ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
            let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! [String:Any]
            self.tableData = jsonResult // WHAT GOES HERE?
        } catch {
            // handle error
        }
    }

And this is my class variable that I want to store my array of dictionaries into:

var tableData = [Dictionary<String, String>]()

How can I correctly store jsonResult into tableData? I do not want to use a struct as the structure of the dictionaries can vary.

Upvotes: 0

Views: 36

Answers (1)

rmaddy
rmaddy

Reputation: 318854

You state the JSON is an array of dictionary but you are casting the result of JSONSerialization.jsonObject to just a dictionary. Since you seem to be expected an array of dictionary with both string keys and values, cast the result accordingly. But do it safely. Never use ! when working with JSON.

if let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [[String:String]] {
    self.tableData = jsonResult
} else {
    // Error - unexpected JSON result
}

This assumes you want the top level of the JSON result. If in fact jsonResult should be a dictionary and that top-level dictionary has a key to the actual array of dictionary you want then you need to fix the code accordingly.

Upvotes: 1

Related Questions