Swift json数据解码

时间:2018-02-05 19:51:26

标签: json parsing swift3

我想在json数据下面解码。我的json数据是这样的:

{
"CourseCode": "xxx",
"ChapterNumber": 1,
"CourseName": "yyy",
"UnitName": "zzz",
"QuestionAnswer": [
    {
        "Index": 1,
        "Question": "bla bla",
        "Answer": "bla bla"
    },
    {
        "Index": 2,
        "Question": "bla bla bla",
        "Answer": "bla bla bla"
    }
}

我的代码是这样的:

class Question{

let question:String
let answer:String
let questionId:Int

init?(json:JSONDictionary){
    guard let question = json["Question"] as? String,
        let answer = json["Answer"] as? String,
        let questionId = json["Index"] as? Int
        else {return nil}

    self.question = question
    self.answer = answer
    self.questionId = questionId

}

static func get(course:String, unit:Int) -> Resource<[Question]>{
    func parser(json: Any) -> [Question]?{
        guard let dictionary = json as? JSONDictionary,
            let dictionaries = dictionary["QuestionAnswer"] as? JSONArray
            else { return nil }
        return dictionaries.flatMap(Question.init)

    }

    let url = URL(string: "www.www")!
    return Resource<[Question]>(url: url, body: nil, method: "GET", parseJSON: parser)

}
deinit { print("\(question) is being deinitialized") }
}

一切都好。但现在我想处理CourseCode,ChapterNumber,CourseName和UnitName。如何为此编辑我的代码?

0 个答案:

没有答案