简体   繁体   English

Swift 4:如何为不同类型的 json 数组实现可编码协议

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

Can somebody enlighten me how to implement codable protocol to swift structs, for the following json array of multiple types?有人可以启发我如何为以下多种类型的 json 数组实现 swift 结构的可codable protocol吗?

In the following json array of materials, it can be reflection object, video or note objects.在下面的 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"
      }
    }
  ]
}

If you can live with a Material that has three optional properties, this is quite straightforward:如果您可以使用具有三个可选属性的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