I am trying to loop through a JSON array which I am getting from an HTTP Request, but I am not sure how.
What I have tried is this:
var request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: Double.infinity)
if Reachability.isConnectedToNetwork(){
request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: Double.infinity);
}
let session = URLSession.shared
var getResp = false
var zinnen : [Zin] = []
let task = session.dataTask(with: request as URLRequest,
completionHandler: { data, response, error -> Void in
let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
for case let data in json {
if let zin = Zin(json: data) {
zinnen.append(zin)
}
}
})
task.resume()
And this is my struct:
struct Zin : CustomStringConvertible {
var description: String
let id : Int
let dutch_sentence : String
let polish_sentence : String
init(dictionary: [String: Any]) {
self.id = dictionary["id"] as? Int ?? 0
self.dutch_sentence = dictionary["dutch_sentence"] as? String ?? ""
self.polish_sentence = dictionary["polish_sentence"] as? String ?? ""
}
}
A sample of the JSON Array:
[
{
"id":"35",
"dutch_sentence":"Ja",
"polish_sentence":"Tak"
},
{
"id":"36",
"dutch_sentence":"Nee",
"polish_sentence":"Nie"
}
]
But in this I get the error
Type '[String: Any]??' does not conform to protocol 'Sequence'
let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]=>let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [[String: Any]]You JSON is an Array of Dictionaries, not a Dictionary so the for loop is weird for a dictionary.