正确地将JSON文件内容加载到swift

时间:2016-03-12 15:51:40

标签: ios arrays json swift nsdictionary

我正在尝试使用以下结构从JSON文件(名为Questions.json)加载测验问题:

{
"Questions":[
                {
                    "questionText": "Is this a question?",
                    "correctAnswer": "Yes",
                    "wrongAnswer1": "No",
                    "wrongAnswer2": "Nope",
                    "wrongAnswer3": "Maybe",
                    "wrongAnswer4": "Unclear"
                },
                {
                   "questionText": "Is this also a question?",
                    "correctAnswer": "Yes",
                    "wrongAnswer1": "No",
                    "wrongAnswer2": "Nope",
                    "wrongAnswer3": "Maybe",
                    "wrongAnswer4": "Unclear"
                }
                ]}

我希望将每个问题(带有问题文本和所有答案选项)加载到我的Question类中,该类包含JSON中的所有属性(questionText,correctAnswer等)

我正在尝试使用此代码将其加载到数组“问题”中:

if let path = NSBundle.mainBundle().pathForResource("Questions", ofType: "json")
    {
        var jsonData: NSData?
        do {
            jsonData = try  NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe)
        } catch _ as NSError {

        }

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: []) as? NSDictionary
                {
                    print(jsonResult)
                    var questions : [Question] = [Question]()
                    questions = jsonResult["Questions"]! as! [Question]
                    print(questions[0].questionText) // ERROR HERE!
                }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    }

当我尝试打印第一个问题文本时,我收到此错误:“致命错误:NSArray元素无法与Swift数组元素类型匹配”

你看到这里有什么问题吗?它甚至是存储问题的好方法吗?

0 个答案:

没有答案