json - swift 4 : how to implement codable protocol for json array of different types

标签 json swift codable

有人可以告诉我如何为以下多种类型的 json 数组实现 swift 结构的可编码协议(protocol)吗?

下面的 Material 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)

关于json - swift 4 : how to implement codable protocol for json array of different types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023988/

相关文章:

java - 当文件大小 > 1GB 时,Gson.toJson 抛出 NullPointerException

c# - 使用 EASYUI 和 Json 创建数据网格,其中数据类型为 Boolean

javascript - 搜索 javascript 对象数组的更有效方法?

ios - CanOpenUrl 方法不适用于 ios 9

ios - Swift 框架集成 - Xcode 显示错误但编译正常

ajax - 需要帮助使用 jQuery AJAX 将复杂对象传递到 ServiceStack

ios - 无法将内容附加到数组

ios - 为什么为某些属性定义 CodingKeys 需要初始化程序?

ios - 无法使用 Codable 和 Alamofire 3.0 解析数据

ios - 在 Swift 4 中解码泛型类的可编码树