2016-12-12 48 views
-1

下面是我試圖解析的JSON的結構。我希望能夠循環訪問這些問題。用SwifyJSON解析JSON

{ 
    "status" : 200, 
    "C&Q" : [ 
    { 
     "category" : "Applicant Details", 
     "questions" : [ 
     { 
      "compulsory" : true, 
      "options" : "Mr.; Mrs.; Miss", 
      "input" : "radio", 
      "question" : "Title" 
     }, 
     { 
      "compulsory" : true, 
      "options" : "N\/A", 
      "input" : "text", 
      "question" : "Surname" 
     } 
     ] 
    }, 
    { 
     "category" : "Identification Documents", 
     "questions" : [ 
     { 
      "compulsory" : true, 
      "options" : "Passport;Drivers License;Voter ID;NHIS", 
      "input" : "radio", 
      "question" : "ID TYPE" 
     }, 
     { 
      "compulsory" : true, 
      "options" : "N\/A", 
      "input" : "date", 
      "question" : "Date of Issue (YYYY-MM-DD)" 
     } 
     ] 
    } 

這是代碼,但我只能通過索引訪問。也許有人可以通過示例代碼來了解如何遍歷以便我可以訪問questions數組。

let swiftyJsonVar = JSON(response.result.value!) 

guard let questions = swiftyJsonVar["C&Q"].arrayValue[0]["questions"].arrayObject as? [[String:AnyObject]] else 
{ 
    print("parsing failed") 
    return 
} 

這是我如何使用/計劃使用數組,它適用於上述解析。

let questionsStructs = questions.map(Questions.init) 
self.formsData = questionsStructs 

任何幫助將不勝感激。

回答

0
var questions:[Question] = [] 
for (key,subJson):(String, JSON) in json["C&Q"] { 
    for (key,j):(String, JSON) in subJson["questions"] { 
     let question = Question(......) 
     questions.append(question) 
    } 
} 
+1

謝謝@ user1941284但是我找不出什麼類型的數組問題[問題]。你能否提供一些更清晰的? –

+0

你想把所有的問題放在一起,或者你想按類別分割它們嗎? – tbilopavlovic

+0

我想要按類別拆分它們。謝謝。 –