SWIFT循环多层级JSON

时间:2016-09-14 14:16:49

标签: ios json swift2

我需要一些帮助来解决这个......

我正在尝试遍历多级或多维JSON对象,然后保存Key&价值数据。

使用以下SWIFT代码,我在致电saveAssessmentData()的行中收到以下错误:Could not cast value of type '__NSCFArray' (0x10ff76d68) to 'NSDictionary' (0x10ff76fe8)

有人可以解释为什么会这样吗?

func saveAssessmentData(testName: String, questionData: NSDictionary, sectionName: String){
// save to core data //
print("Saving Section: \(sectionName) for test: \(testName) QuestionData: \(questionData)")
}

let tests = "{\"testOne\":[{\"sectionOne\":[{\"questionOne\":\"for loops swift\",\"Answer\":\"I dont have one\"},\"questionTwo\":\"for loops swift\",\"Answer\":\"I still dont have one\"},\"questionThree\":\"for loops swift\",\"Answer\":\"Third time is not the charm\"}]}],\"testTwo\":[{\"sectionOne\":[{\"questionOne\":\"for loops swift\",\"Answer\":\"I dont have one\"},\"questionTwo\":\"for loops swift\",\"Answer\":\"I still dont have one\"},\"questionThree\":\"for loops swift\",\"Answer\":\"Third time is not the charm\"}]}],\"testThree\":[{\"sectionOne\":[{\"questionOne\":\"for loops swift\",\"Answer\":\"I dont have one\"},\"questionTwo\":\"for loops swift\",\"Answer\":\"I still dont have one\"},\"questionThree\":\"for loops swift\",\"Answer\":\"Third time is not the charm\"}]}]}"

let JSONstring = tests.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

let JSON = try NSJSONSerialization.JSONObjectWithData(JSONstring!, options:[]) as! NSDictionary

for (testName, testSections) in JSON{

    for (sectionName, questionData) in testSections as! NSDictionary{
        print("\(sectionName) has \(questionData.count) questions")

        saveAssessmentData(testName as! String, questionData: questionData as! NSDictionary, sectionName: sectionName as! String)
    }

}

0 个答案:

没有答案