Swift如何使用可编码协议解析字符串数组

时间:2020-05-13 14:00:56

标签: json swift parsing codable

这是我的“包装”类:

class QuestionResult: Codable {

    var title: String?
    var questions: [Question]?
}

问题课:

class Question: Codable{

    var question_id: Int?
    var question_type: String?
    var question: String?
    var answers: [String]?   
}

这是相对的JSON:

{
   "title":"sondaggio di test",
   "start_message":"<p>sodaggio di prova</p>\r\n",
   "end_message":"<p>fine sondaggio di test</p>\r\n",
   "start_date":"2020-05-01",
   "end_date":"2020-05-22",
   "voted":false,
   "questions":[
      {
         "question_id":418,
         "question_type":"number",
         "question":"domanda test 1"
      },
      {
         "question_id":419,
         "question_type":"checkbox",
         "question":"domanda test 2",
         "answers":[
            "risp1",
            "risp2",
            "risp3",
            "risp4",
            "risp5"
         ]
      }
   ]
}

现在,除返回nil的“ answers”属性外,所有属性均已正确解析。 如何使用Codable协议解析字符串数组?

1 个答案:

答案 0 :(得分:0)

这是模型:

struct QuestionResult: Codable {
    let title, startMessage, endMessage, startDate: String
    let endDate: String
    let voted: Bool
    let questions: [Question]

    enum CodingKeys: String, CodingKey {
        case title
        case startMessage = "start_message"
        case endMessage = "end_message"
        case startDate = "start_date"
        case endDate = "end_date"
        case voted, questions
    }
}

struct Question: Codable {
    let questionID: Int
    let questionType, question: String
    let answers: [String]?

    enum CodingKeys: String, CodingKey {
        case questionID = "question_id"
        case questionType = "question_type"
        case question, answers
    }
}

我不认为您的模型有任何问题。但是请尝试使用以下代码来确保:

let result = try? JSONDecoder().decode(QuestionResult.self, from: data)
print(result?.questions[1].answers)