簡體   English   中英

Swift 如何使用可編碼協議解析字符串數組

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

這是我的“包裝”class:

class QuestionResult: Codable {

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

問題 class:

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 的“答案”屬性之外,所有屬性都已正確解析。 如何使用 Codable 協議解析字符串數組?

這是 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
    }
}

無論如何,我不認為您的 model 是錯誤的。 但請嘗試此代碼以確保:

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