使用Freddy SDK解析JSON文件

时间:2017-02-16 00:32:26

标签: json swift swift3

在使用Freddy SDK解析JSON文件时,我正在努力以正确的格式获取某些值,我正在尝试使用JSON来解析一些问题和答案:

  {
      "success":true,
      "quiz":[
              {
              "question":"Which of the following is required by law?",
              "answers":[
                         ["To have your dog microchipped and correct details.", true],
                         ["To have your dog wear a collar and tag with correct contact details.", true],
                         ["To register your dog with the local Dog Warden.", false],
                         ["To pick up after your dog.", true]
                         ],
              "imageFileName":"ChippedDog.jpg"
              }
             ]
  }

我遇到的麻烦在于获得答案及其Bool值。我的解析代码是:

func createQuestionObjectsFromJSON() -> [Question] {

    self.questions = []
    let filePath = Bundle.main.path(forResource: self.fileName, ofType: self.fileType)
    if let data = NSData(contentsOfFile:filePath!) {
        do {
            let json = try JSON(data: data as Data)
            for questionJSON in try json.getArray(at:"quiz") {

                var question = Question()
                question.text = try questionJSON.getString(at: "question")
                question.answers = try questionJSON.getArray(at: "answers") as [AnyObject]
                question.imageFileName = try questionJSON.getString(at: "imageFileName")
                self.questions?.append(question)
            }
        } catch {
            print("Error parsing questions part of JSON file")
        }
    }

    return questions

}

但是当我尝试访问我的cellForRow中的每个答案时,我不能。

如果打电话

let answer = currentQuestion.answers[indexPath.row]

然后将其打印出来

[To have your dog microchipped and correct details., true]

但第一个值不是字符串,如果我调用

answer[0]

我没有。我有点失落,确定有一个简单的修复,但我只是看不到它。

任何帮助都会很棒。

更新:Qustion struct:

导入UIKit

struct Question {

    var text: String!
    var answers: [AnyObject]!
    var imageFileName: String!
}

1 个答案:

答案 0 :(得分:0)

尝试 question.answers = try questionJSON.getArray(at: "answers") as [Array]


而不是 question.answers = try questionJSON.getArray(at: "answers") as [AnyObject]