MattBlack MattBlack - 2 months ago 101
JSON Question

JSON serialization with Swift 3

I am trying to to populate a table by filling an array from JSON data. I am using the code below but keep getting the error:


Type 'Any' has no subscript members


on the following lines of code:

self.tableData.append(jsonResult[i]["title"]! as! String)
self.tableImages.append(jsonResult[i]["image"]! as! String)
self.tableDesc.append(jsonResult[i]["description"]! as! String)
self.tableValidity.append(jsonResult[i]["validity"]! as! String)


My code:

let str3 = Int(str2!)!
let url = NSURL(string: "https://www.*****.php")!

let task = URLSession.shared.dataTask(with: url as URL) { (data, response, error) -> Void in
if let urlContent = data {
do {

let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)


print(str3)

var i = 0

while i < str3 {
print(jsonResult[i]["title"]! as!String)
print(jsonResult[i]["image"]! as! String)

self.tableData.append(jsonResult[i]["title"]! as! String)
self.tableImages.append(jsonResult[i]["image"]! as! String)
self.tableDesc.append(jsonResult[i]["description"]! as! String)
self.tableValidity.append(jsonResult[i]["validity"]! as! String)

i = i + 1

}

} catch {
print("JSON serialization failed")
}

} else {
print("ERROR FOUND HERE")
}

DispatchQueue.main.async(execute: { () -> Void in

self.tableView.reloadData()

})

}

task.resume()

Answer

The compiler doesn't know the type of jsonResult, you have to tell what it is, for example with optional binding like this:

if let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as? [[String:AnyObject]] {


}

Here I downcast the JSON as an array of dictionaries. Use your loop inside this if let and it should work.

Comments