2017-02-10 1 views
-2
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! 
+1

Neigt Versuchen Sie nicht NSArray/NSDictionary zu verwenden (vor allem wenn man zwei Würfe tun: 'so! [String: Alles]! Als NSDictionary'), Swift-Typen verwenden. Außerdem müssen Sie angeben, welche Zeile das Problem verursacht. Ich nehme an, dass Ihr Problem in den Zeilen 'let questionName' steht? Wenn ja, frage dich: 'Fragen 'ist ein' NSArray'. Aber wer hat dem Compiler gesagt, dass 'question [i]' ein Dictionary ist und Sie auf seine Daten mit '[" ques "]' 'zugreifen können? – Larme

+0

danke für Ihre Anleitung –

Antwort

1

versuchen, dies ..

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 

Und bitte Kraft unwrap nicht machen .. Dieser Code ist nur für Ihre Orientierung.

0
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) 
} 
Verwandte Themen