do{
//converting response to NsDictionary
var myJSON:NSDictionary!
myJSON=try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any] as NSDictionary!
//getting the json response
let questions:NSArray = myJSON["questions"] as! NSArray
//looping through all the array
for i in 0 ..< questions.count{
//getting the json for each index
//let i=0
self.questionId = questions[i]["id"] as! Int
let questionName:String = questions[i]["ques"] as! String?
let questionopta:String = questions[i]["opta"] as! String!
let questionoptb:String = questions[i]["optb"] as! String!
let questionoptc:String = questions[i]["optc"] as! String!
let questionoptd:String = questions[i]["optd"] as! String!
try this ..
do{
var myJSON:[String:Any]!
myJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
//getting the json response
let questions = myJSON["questions"] as! [[String:Any]]
//looping through all the array
for obj in questions{
self.questionId = obj["id"] as! Int
let questionName = obj["ques"] as! String
let questionopta = obj["opta"] as! String
let questionoptb = obj["optb"] as! String
let questionoptc = obj["optc"] as! String
let questionoptd = obj["optd"] as! String
And please don't make force unwrap .. this code is just for your guidance.
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String : Any] {
for question in json["questions"] as? [[String : Any]] ?? [] {
guard
let questionId = question["quid"] as? Int,
let questionName = question["ques"] as? String,
let questionopta = question["opta"] as? String,
let questionoptb = question["optb"] as? String,
let questionoptc = question["optc"] as? String,
let questionoptd = question["optd"] as? String else { continue }
self.questionId = questionId
// ...
}
}
} catch {
print(error)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.