簡體   English   中英

Swift 4:如何為不同類型的 json 數組實現可編碼協議

[英]Swift 4: how to implement codable protocol for json array of different types

有人可以啟發我如何為以下多種類型的 json 數組實現 swift 結構的可codable protocol嗎?

在下面的 json 材質數組中,可以是反射對象、視頻或筆記對象。

{
  "materials": [
    {
      "reflection": {
        "title": "3-2-1 reflection",
        "description": "please reflect after today",
        "questions": [
          {
            "question": "question 1",
            "answer": "answer 1",
            "answerImageUrl": "http://xxx"
          },
          {
            "question": "question 1",
            "answer": "answer 1",
            "answerImageUrl": "http://xxx"
          }
        ]
      }
    },
    {
      "video": {
        "title": "the jungle",
        "description": "please watch after today lesson",
        "videoUrl": "http://"
      }
    },
    {
      "note": {
        "title": "the note",
        "description": "please read after today lesson"
      }
    }
  ]
}

如果您可以使用具有三個可選屬性的Material ,這將非常簡單:

struct Response: Codable {
    let materials: [Material]
}

struct Material: Codable {
    let reflection: Reflection?
    let video: Video?
    let note: Note?
}

struct Video: Codable {
    let title, description, videoUrl: String
}

struct Reflection: Codable {
    let title, description: String
    let questions: [Question]
}

struct Question: Codable {
    let question, answer, answerImageUrl: String
}

struct Note: Codable {
    let title, description: String
}

let response = JSONDecoder().decode(Response.self, from: data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM