This is my "wrapper" class:
class QuestionResult: Codable {
var title: String?
var questions: [Question]?
}
Question class:
class Question: Codable{
var question_id: Int?
var question_type: String?
var question: String?
var answers: [String]?
}
and this is the relative 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"
]
}
]
}
Now, all properties has been parsed correctly except for the "answers" properties that return nil. How can I parse an array of strings using Codable protocol?
Here is the model:
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
}
}
I don't think your model is wrong in anyway. But try this code to make sure:
let result = try? JSONDecoder().decode(QuestionResult.self, from: data)
print(result?.questions[1].answers)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.