简体   繁体   English

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

[英]Swift How to parse string array using Codable Protocol

This is my "wrapper" class:这是我的“包装”class:

class QuestionResult: Codable {

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

Question class:问题 class:

class Question: Codable{

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

and this is the relative JSON:这是相对的 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.现在,除了返回 nil 的“答案”属性之外,所有属性都已正确解析。 How can I parse an array of strings using Codable protocol?如何使用 Codable 协议解析字符串数组?

Here is the model:这是 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.无论如何,我不认为您的 model 是错误的。 But try this code to make sure:但请尝试此代码以确保:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM