Lenny Lenny - 3 months ago 47
Swift Question

Read JSON format out of webpage in SWIFT 3

I'm trying to fetch data out of a JSON file on my webserver. In previous versions of SWIFT this worked out:

self.url = "https://www.example.com/example"
let requestURL: URL = URL(string: self.url)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in

let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode

if (statusCode == 200) {

do{

let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]]

if let stations = json["ticket"] as? [[String: AnyObject]] {

for station in stations! {

if let status = station["status"] as? String {
self.resultStatus = status

if let name = station["name"] as? String {
self.clientName = name

if let type = station["type"] as? String {
self.ticketType = type
self.setThemeResult()
}
}
}
}

}

} catch {
print("Error with Json: \(error)")
}

}
}
task.resume()


Well... I know that it's probably a bit messy, but it did work. :) In SWIFT 3, xcode made some changes to the code.
This:

let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]]


Became:

let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String: AnyObject]]


But now, this error appears.
this

And I't would be amazing if someone can explain what it means, and maybe come up with a solution.

Thanks in advance.

PS:
I'm aware that there are some questions on this forum that could possibly contain the answer for my problem already. I'm just too new to programming in SWIFT that I have to ask a question about my particular case to find the answer.

Answer

I think your response is Dictionary not Array, so you need to write [String: Any] instead of [[String: Any]]

 let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
 if let stations = json["ticket"] as? [[String: Any]] {

 }

Note: If your response is Array than try access first object of array to get dictionary.

 if let stations = json[0]["ticket"] as? [[String: Any]] {

 }