有人可以告诉我如何为以下多种类型的 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/